Search code examples
javascriptjsonloopsyamlmustache

Json mustache for loop range: 1 to 1000


I am using .yaml and json.mustaches to build aws cloudformation templates.

I dont want to hardcode a list of 4040, 4041...etc 1000 times Does mustache have concept of loop logic? ie I want a loop from 4040 to 5040. I imagine i could just specify start and end of the range and have the mustache generate the sequence.

desired output:

{
    "InstancePort": 4040,
    "LoadBalancerPort": 4040,
    "Protocol": "HTTPS", "InstanceProtocol": "HTTPS"
},        
{
    "InstancePort": 4041,
    "LoadBalancerPort": 4041,
    "Protocol": "HTTPS", "InstanceProtocol": "HTTPS"
},        
{
    "InstancePort": 4042,
    "LoadBalancerPort": 4042,
    "Protocol": "HTTPS", "InstanceProtocol": "HTTPS"
}   

...etc till 5040


Solution

  • You can use the Section template, like this:

    {{#ports}}
    {
      "InstancePort": {{port}},
      "LoadBalancerPort": {{port}},
      "Protocol": "HTTPS", "InstanceProtocol": "HTTPS"
    }   
    {{/ports}}
    

    And in your Javascript have the following data:

    ports: [...Array(1000).keys()].map(i => { return { port: i + 4040 }});
    

    The above ES6 map will generate 1000 numbers, starting at 4040 through to 5040.

    Edit: Updated to include the correct attribute!