mustache / mustache.github.com

The {{official}} website
http://mustache.github.io/
Other
2.32k stars 293 forks source link

Help with sections #123

Closed wojciechgizynski closed 4 years ago

wojciechgizynski commented 5 years ago

Hi, I need some help preparing a template. I have the following hash:

{
    "key": "value123"
}

I want to print Value is: value123 only if there is key in the hash. How would I do that?

{{#key}}
Value is {{XXX}}.
{{/key}}
{{^key}}
No key, no value!
{{/key}}

What should I put in place of XXX to get the desired output? In other words, how do I display the value of a hash key that I based the section on, rather than a nested key value?

I know that if the case would be

{
   "key":  { "door":  "value123" }
}

I could do

{{#key}}
Value is {{door}}.
{{/key}}
{{^key}}
No key, no door, no value!
{{/key}}

It's just not what I need right now.

jobol commented 5 years ago

Really good question! For the library I maintain (https://gitlab.com/jobol/mustach) I added an extension for that behaviour: the single dot: when you put . for XXX it works as you expect. Subito I realize that this is not documented. See:

$ cat > ta.j
{
   "key":  { "door":  "value123" }
}

$ cat > ta.t
{{#key}}
Value is {{.}}.
{{/key}}
{{^key}}
No key, no value!
{{/key}}

$ mustach ta.j ta.t

Value is { "door": "value123" }.
wojciechgizynski commented 5 years ago

Thanks for the response. I'm preparing a Slack notification template from Kibana Alerts and it uses mustache. I don't have an option of using another library.

wojciechgizynski commented 4 years ago

Nevermind, it's actually perfectly doable with simple:

{{#key}}
Value is {{key}}.
{{/key}}

Not sure how I've missed this.