Skip to content

Instantly share code, notes, and snippets.

@cap10morgan
Last active August 29, 2015 14:16
Show Gist options
  • Save cap10morgan/506a438562815ab156c0 to your computer and use it in GitHub Desktop.
Save cap10morgan/506a438562815ab156c0 to your computer and use it in GitHub Desktop.
Awkward Mustache Examples
;; Nested data in tokens
(def template
"{{#parent}}
{{child1}}
{{child2}}
{{#child3}}
{{grandchild}}
{{/child3}}
{{/parent}}")
(render-string template
{:parent
{:child1 "I'm the first child"
:child2 "I'm the middle child"
:child3 {:grandchild "I'm the grandkid"}}}) ; =>
" I'm the first child
I'm the middle child
I'm the grandkid
"
;; Versus Selmer
(def template
"{{parent.child1}}
{{parent.child2}}
{{parent.child3.grandchild}}")
(render template
{:parent
{:child1 "I'm the first child"
:child2 "I'm the middle child"
:child3 {:grandchild "I'm the grandkid"}}}) ; =>
"I'm the first child
I'm the middle child
I'm the grandkid"
;; Treating the first of many items differently
(def template
"{{#items}}
{{#first}}
<li>I'm the first - {{name}}</li>
{{/first}}
{{^first}}
<li>I'm one of the others - {{name}}</li>
{{/first}}
{{/items}}")
(render-string template
{:items
[
{:name "First one" :first true ; <- ew
}
{:name "2nd"}
{:name "Third"}
{:name "Fourth" :first true ; <- oops
}
]
}) ; =>
" <li>I'm the first - First one</li>
<li>I'm one of the others - 2nd</li>
<li>I'm one of the others - Third</li>
<li>I'm the first - Fourth</li>
"
;; Versus Selmer
(def template
"{% for item in items %}
{% if forloop.first %}
<li>I'm the first - {{item.name}}</li>
{% else%}
<li>I'm one of the others - {{item.name}}</li>
{% endif %}
{% endfor %}")
(render template
{:items
[
{:name "First one"}
{:name "2nd"}
{:name "Third"}
{:name "Fourth"}
]
}) ; =>
"
<li>I'm the first - First one</li>
<li>I'm one of the others - 2nd</li>
<li>I'm one of the others - Third</li>
<li>I'm one of the others - Fourth</li>
"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment