StubbleOrg / Stubble

Trimmed down {{mustache}} templates in .NET
Other
405 stars 58 forks source link

Repeat sections #72

Closed Tasteful closed 5 years ago

Tasteful commented 5 years ago

When creating templates I sometimes have the need to repeat the sections X amount of times. If we see the current sections implementation it handle number as if-condition (0 = false,other value = true). If the section got a list or dictionary as value the template is iterating over the items in the value.

Is there any possibility today to do something like this? Is it possible to add the feature into the SectionTokenRenderer so they from the input data; when a number that is positive value, creating a list of items that is used?

Example data:

{
  "count": 5
}

With template:

{{#count}}
  Item {{.}}
{{/count}}

Should generate:

  Item 1
  Item 2
  Item 3
  Item 4
  Item 5
Romanx commented 5 years ago

Hey,

Thanks for posting this. The core of Stubble is to provide an accurate and fast implementation of the mustache language without any "extra" functionality by default. Since this would be a deviation from that we wouldn't include it in the base library.

Since this seems like a rather niche usecase you could extend SectionTokenRenderer with your own implementation and replace it using the pipeline configuration you added in your recent pull request.

An alternative might be adding block scope helper methods to Stubble.Helpers so you could wrap your template in a helper than repeats the content multiple times like this:

{{#repeat count }}
  Item {{.}}
{{/repeat}}

The helpers library doesn't include this functionality but it may be something worth looking at, please feel free to open an issue over there to discuss it since we want to be sure there are other valid use cases