Aller au contenu principal

Modèles

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

Chaque segment possède une propriété template pour personnaliser le texte affiché. Sous le capot, cela utilise la fonctionnalité text/template de Go étendue avec sprig, qui offre plusieurs propriétés standards à utiliser.

Propriétés globales

Ces propriétés peuvent être utilisées partout, dans n'importe quel segment. Si un segment contient une propriété du même nom, la valeur de la propriété du segment sera utilisée. Pour utiliser explicitement la propriété globale, vous pouvez la préfixer par .$.

NameTypeDescription
.Rootbooleanis the current user root/admin or not
.PWDstringthe current working directory (~ for $HOME)
.AbsolutePWDstringthe current working directory (unaltered)
.PSWDstringthe current non-filesystem working directory in PowerShell
.Folderstringthe current working folder
.Shellstringthe current shell name. The value may be overriden by [maps.shell_name][maps].
.ShellVersionstringthe current shell version
.SHLVLintthe current shell level
.UserNamestringthe current user name
.HostNamestringthe host name
.Codeintthe last exit code
.Jobsintnumber of background jobs (only available for zsh, PowerShell, and Nushell)
.OSstringthe operating system
.WSLbooleanin WSL yes/no
.Templatesstringthe [templates][templates] result
.PromptCountintthe prompt counter, increments with 1 for every prompt invocation
.Versionstringthe Oh My Posh version
.SegmentSegmentthe current segment's metadata

Segment

NameTypeDescription
.Segment.Indexintthe current segment's index (as rendered)
.Segment.Textstringthe segment's rendered text

Variables d'environnement

NameTypeDescription
.Env.VarNamestringAny environment variable where VarName is the environment variable name
astuce

Pour les shells ci-dessous, vous pouvez surcharger une fonction pour exécuter une logique avant l'affichage du prompt. Cela peut servir, par exemple, à peupler une variable d'environnement avec un contexte spécifique.

function Set-EnvVar([bool]$originalStatus) {
$env:POSH=$(Get-Date)
}
New-Alias -Name 'Set-PoshContext' -Value 'Set-EnvVar' -Scope Global -Force

Variables de configuration

NameTypeDescription
.Var.VarNameanyAny config variable where VarName is the variable name

Exemple

{
"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 }} "
}
]
}
]
}

Logique des templates

TemplateDescription
{{.}}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).

Fonctions utilitaires

Sprig

Oh My Posh inclut toutes les fonctions sprig, vous permettant d'effectuer des opérations sur les chaînes, chemins et bien d'autres manipulations directement dans vos templates. Consultez leur documentation pour découvrir les options disponibles et leur utilisation.

Personnalisées

TemplateDescription
{{ url .UpstreamIcon .UpstreamURL }}Create an OSC8 hyperlink to a website to open your default browser (needs terminal [support][terminal-list-hyperlinks]).
{{ path .Path .Location }}Create an OSC8 file link to a folder to open your file explorer (needs terminal [support][terminal-list-hyperlinks]).
{{ 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).

Propriétés de templates entre segments

Pour utiliser les propriétés d'un autre segment dans un template, utilisez {{ .Segments.Segment }}.Segment correspond au nom du segment cible avec sa première lettre en majuscule.

Si vous souhaitez par exemple utiliser la propriété .UpstreamGone du segment git dans le segment [status][status], procédez ainsi :

{
"template": " {{ if .Segments.Git.UpstreamGone }}{{ else if gt .Code 0 }}{{ else }}{{ end }} "
}
attention

Pour que cela fonctionne, le segment référencé doit figurer dans votre configuration. L'exemple ci-dessus ne fonctionnera pas si votre configuration ne contient pas de segment git, car Oh My Posh ne remplit les propriétés que lorsque nécessaire.

astuce

Si vous avez deux segments identiques pour des usages différents, utilisez la propriété alias sur le segment pour les distinguer.

{
"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 }}"
}
]
}

Pour vérifier si un segment spécifique est actif, utilisez la fonction .Segments.Contains, par exemple :

{
"template": "{{ if .Segments.Contains \"Git\" }}{{ else if gt .Code 0 }}{{ else }}{{ end }} "
}

Décoration du texte

Utilisez la syntaxe suivante pour décorer du texte :

SyntaxDescription
<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

Ceci est utilisable dans les templates et les icônes/textes de votre configuration.