Sometimes you have nested loops suitable for a tree-view kind of display. For example:
{
qtys: {
'2016': {
'03': [111, 112, 113],
'12': [121, 122, 123]
},
'2018': {
'05': [211, 212, 213],
'09': [221, 222, 223]
},
},
}
And you want to display it like this:
<ul>{{@qtys}}
<li>{{=_key}}
<ul>{{@_val}}
<li>{{=_key}}
<ul>{{@_val}}
<li>{{=_val}}</li>
{{/@_val}}</ul>
</li>
{{/@_val}}</ul>
</li>
{{/@qtys}}</ul>
The problem is that the blockregex
will match the first {{@_val}}
with the very first {{/@_val}}
it finds, not the second one, which is the correct one.
I've found a relatively easy solution to this by a minor tweek to the regular expression. Here you have both the original and my suggested one:
var blockregex = /\{\{(([@!]?) (.+?) )\}\}(([\s\S]+?)(\{\{:\1\}\}([\s\S]+?))?)\{\{\/\1\}\}/g,
var blockregex = /\{\{(([@!]?)([\.\w]+)[\s\S]*?)\}\}(([\s\S]+?)(\{\{:\1\}\}([\s\S]+?))?)\{\{\/\1\}\}/g;
I left a couple of gaps in the original one to highlight the change, just a few characters.
What it does is to allow an optional label in the placeholder to clearly specify the matching tags, like this:
<ul>{{@qtys}}
<li>{{=_key}}
<ul>{{@_val year}}
<li>{{=_key}}
<ul>{{@_val month}}
<li>{{=_val}}</li>
{{/@_val month}}</ul>
</li>
{{/@_val year}}</ul>
</li>
{{/@qtys}}</ul>
The labels (year
, month
) are optional and can be omitted (like in {{@qtys}}
which is not ambiguous).
The label can be separated from the tag by anything other but a valid variable name, that is, it doesn't need to be a space, you could write {{@_val-month}}
and it would do just fine. As a matter of fact, the space (or any separator) is part of the label. The exact label, including the separator spaces or whatever was used must be replicated verbatim on the closing tag, thus, a single space before and none after the label is preferred for clarity and consistency. I omitted checking for spaces so to add as fewest bytes to the already small size of the library.
Well chosen labels can help document what _val
actually stands for.
This issue is actually a suggestion and requires no reply. Feel free to close. (and thanks for this little, really little, gem)