Plantillas
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Cada segmento tiene una propiedad template para personalizar el texto que se muestra.
Internamente, utiliza la función text/template de Go extendida con sprig,
ofreciendo varias propiedades estándar para trabajar.
Propiedades globales
Estas propiedades pueden usarse en cualquier segmento. Si un segmento contiene una propiedad con el mismo nombre,
se usará el valor de la propiedad del segmento. Para usar la propiedad global, puedes anteponer
.$ para referenciarla directamente.
| Name | Type | Description |
|---|---|---|
.Root | boolean | is the current user root/admin or not |
.PWD | string | the current working directory (~ for $HOME) |
.AbsolutePWD | string | the current working directory (unaltered) |
.PSWD | string | the current non-filesystem working directory in PowerShell |
.Folder | string | the current working folder |
.Shell | string | the current shell name. The value may be overriden by maps.shell_name. |
.ShellVersion | string | the current shell version |
.SHLVL | int | the current shell level |
.UserName | string | the current user name |
.HostName | string | the host name |
.Code | int | the last exit code |
.Jobs | int | number of background jobs (only available for zsh, PowerShell, and Nushell) |
.OS | string | the operating system |
.WSL | boolean | in WSL yes/no |
.Templates | string | the templates result |
.PromptCount | int | the prompt counter, increments with 1 for every prompt invocation |
.Version | string | the Oh My Posh version |
.Segment | Segment | the current segment's metadata |
Segmento
| Name | Type | Description |
|---|---|---|
.Segment.Index | int | the current segment's index (as rendered) |
.Segment.Text | string | the segment's rendered text |
Variables de entorno
| Name | Type | Description |
|---|---|---|
.Env.VarName | string | Any environment variable where VarName is the environment variable name |
Para los siguientes shells, puedes sobrescribir una función para ejecutar lógica antes de que se muestre el prompt. Esto puede usarse, por ejemplo, para llenar una variable de entorno con un contexto específico.
- powershell
- zsh
- bash
- fish
- nu
function Set-EnvVar([bool]$originalStatus) {
$env:POSH=$(Get-Date)
}
New-Alias -Name 'Set-PoshContext' -Value 'Set-EnvVar' -Scope Global -Force
function set_poshcontext() {
export POSH=$(date)
}
function set_poshcontext() {
export POSH=$(date)
}
function set_poshcontext
set --export POSH $(date)
end
$env.SET_POSHCONTEXT = {
$env.POSH = ( date now );
}
Variables de configuración
| Name | Type | Description |
|---|---|---|
.Var.VarName | any | Any config variable where VarName is the variable name |
Ejemplo
- json
- yaml
- toml
{
"version": 4,
"var": {
"Hello": "hello",
"World": "world"
},
"blocks": [
{
"type": "prompt",
"alignment": "left",
"segments": [
{
"type": "text",
"style": "plain",
"foreground": "p:white",
"template": "{{ .Var.Hello }} {{ .Var.World }} "
}
]
}
]
}
version: 4
var:
Hello: hello
World: world
blocks:
- type: prompt
alignment: left
segments:
- type: text
style: plain
foreground: p:white
template: "{{ .Var.Hello }} {{ .Var.World }} "
version = 4
[var]
Hello = "hello"
World = "world"
[[blocks]]
type = "prompt"
alignment = "left"
[[blocks.segments]]
type = "text"
style = "plain"
foreground = "p:white"
template = "{{ .Var.Hello }} {{ .Var.World }} "
Lógica de plantillas
| Template | Description |
|---|---|
{{.}} | Root element. |
{{.Var}} | Variable in a struct, where Var is a variable. |
{{- .Var -}} | Remove extra white space surrounding the .Var variable and remove the newline. Either side is fine too. |
{{ $planet := "Earth"}} | {{ $planet }} Store a value in a custom variable to reference later. Note that .$ is used to reference the global/parent context, like in the full example below with $. |
Hi {{if .Name}} {{.Name}} {{else}} visitor {{end}} | If-else statement. If will evaluate whether or not the argument is empty. Using the elseif conditional is also an option. The not negation is available too. |
{{if and .Arg1 .Arg2}} both complete. {{else}} incomplete. {{end}} | The and function compares multiple arguments to return the boolean AND (if arg1 then arg2 else arg1). Both arguments are evaluated. The or function compares multiple arguments to return the boolean OR. Similar to if arg1 then arg1 else arg2, so arg2 will never be evaluated if arg1 is false (not empty). |
{{with .Var}} {{end}} | With statement, where Var is a variable. It skips the block if the variable is absent. |
{{range .Array}} {{end}} | Range statement, where Array is an array, slice, map, or channel. |
{{ lt 3 4 }} | This lt comparison function evaluates to true since 3 is less than 4 (other boolean operators: eq, ne, lt, le, gt, ge). |
Funciones auxiliares
Sprig
Oh My Posh incluye todas las funciones de sprig, permitiendo operar con cadenas, rutas y otras manipulaciones directamente desde tu plantilla. Consulta su documentación para ver las opciones disponibles y cómo usarlas.
Personalizadas
| Template | Description |
|---|---|
{{ url .UpstreamIcon .UpstreamURL }} | Create an OSC8 hyperlink to a website to open your default browser (needs terminal support). |
{{ path .Path .Location }} | Create an OSC8 file link to a folder to open your file explorer (needs terminal support). |
{{ secondsRound 3600 }} | Round seconds to a time indication. In this case the output is 1h. |
{{ if glob "*.go" }}OK{{ else }}NOK{{ end }} | Exposes filepath.Glob as a boolean template function. |
{{ if matchP ".*\\.Repo$" .Path }}Repo{{ else }}No Repo{{ end }} | Exposes regexp.MatchString as a boolean template function. |
{{ replaceP "c.t" "cut code cat" "dog" }} | Exposes regexp.ReplaceAllString as a string template function. |
{{ .Code | hresult }} | Transform a status code to its HRESULT value for easy troubleshooting. For example -1978335212 becomes 0x8A150014. |
{{ readFile ".version.json" }} | Read a file in the current directory. Returns a string. |
{{ random (list \"a\" 2 .MyThirdItem) }} | Selects a random element from a list. The list can be an array or slice containing any types (use sprig's list). |
Propiedades entre segmentos
Para usar propiedades de otro segmento en una plantilla, utiliza {{ .Segments.Segment }}
donde .Segment es el nombre del segmento objetivo con la primera letra en mayúscula.
Por ejemplo, para usar la propiedad .UpstreamGone del segmento git en el segmento status:
- json
- yaml
- toml
{
"template": " {{ if .Segments.Git.UpstreamGone }}{{ else if gt .Code 0 }}{{ else }}{{ end }} "
}
template: " {{ if .Segments.Git.UpstreamGone }}{{ else if gt .Code 0 }}{{ else
}}{{ end }} "
template = " {{ if .Segments.Git.UpstreamGone }}{{ else if gt .Code 0 }}{{ else }}{{ end }} "
Para que esto funcione, el segmento al que haces referencia debe estar en tu configuración. El ejemplo anterior no funcionará si tu configuración no contiene un segmento git, ya que Oh My Posh solo completa las propiedades cuando es necesario.
Si tienes segmentos idénticos con distintos propósitos, usa la propiedad alias para diferenciarlos.
- json
- yaml
- toml
{
"segments": [
{
"type": "git",
"alias": "GitMain",
"style": "plain",
"foreground": "#ffffff",
"options": {
"branch_icon": ""
}
},
{
"type": "git",
"alias": "GitSecondary",
"style": "plain",
"foreground": "#ffffff",
"options": {
"branch_icon": ""
}
},
{
"type": "text",
"style": "plain",
"foreground": "#ffffff",
"template": "{{ .Segments.GitMain.HEAD }} - {{ .Segments.GitSecondary.HEAD }}"
}
]
}
segments:
- type: git
alias: GitMain
style: plain
foreground: "#ffffff"
options:
branch_icon: ""
- type: git
alias: GitSecondary
style: plain
foreground: "#ffffff"
options:
branch_icon: ""
- type: text
style: plain
foreground: "#ffffff"
template: "{{ .Segments.GitMain.HEAD }} - {{ .Segments.GitSecondary.HEAD }}"
[[segments]]
type = "git"
alias = "GitMain"
style = "plain"
foreground = "#ffffff"
[segments.options]
branch_icon = ""
[[segments]]
type = "git"
alias = "GitSecondary"
style = "plain"
foreground = "#ffffff"
[segments.options]
branch_icon = ""
[[segments]]
type = "text"
style = "plain"
foreground = "#ffffff"
template = "{{ .Segments.GitMain.HEAD }} - {{ .Segments.GitSecondary.HEAD }}"
Para verificar si un segmento específico está activo, usa la función .Segments.Contains, por ejemplo:
- json
- yaml
- toml
{
"template": "{{ if .Segments.Contains \"Git\" }}{{ else if gt .Code 0 }}{{ else }}{{ end }} "
}
template: '{{ if .Segments.Contains "Git" }}{{ else if gt .Code 0 }}{{ else
}}{{ end }} '
template = "{{ if .Segments.Contains \"Git\" }}{{ else if gt .Code 0 }}{{ else }}{{ end }} "
Decoración de texto
Puedes decorar texto usando esta sintaxis:
| Syntax | Description |
|---|---|
<b>bold</b> | bold as bold text |
<u>underline</u> | underline as underlined text |
<o>overline</o> | overline as overlined text |
<i>italic</i> | italic as italic text |
<s>strikethrough</s> | strikethrough as strikethrough text |
<d>dimmed</d> | dimmed as dimmed text |
<f>blink</f> | blink as blinking (flashing) text |
<r>reversed</r> | reversed as reversed text |
Esto funciona tanto en plantillas como en íconos/texto dentro de tu configuración.