Stan
Stan

Reputation: 26511

Jade interpret variables in loop

I have a simple block that repeats four times and every block will have corresponding variables names that will increase by 1.

So I thought maybe I can just loop 4 times and somehow interpret the variables so it would work instead of copying the block 4 times and changing variable names programatically.

Here is an example of my block

div.tile_content.tile_tax_form_bottom_bar
    h3.form_headline!= keys.global.faq
    div#tax.panel-group.custom-panel
        div.panel.panel-default
            div.panel-heading
                h4.panel-title
                    a.collapsed(href='#tax-1', data-toggle='collapse', data-parent='#tax')
                        i.fa.fa-times-circle
                        i.fa.fa-plus-circle
                        != keys.tax.faq_q1
            div#tax-1.panel-collapse.collapse
                div.panel-body
                    p!= keys.tax.faq_a1

As you can see I have some id parameters as tax-{i} but the bigger problem is the keys object that stores the translations e.g. keys.tax.faq_a{i}.

Would something like that be possible or should I just copy it four times and make it hard-coded instead?

Upvotes: 3

Views: 480

Answers (1)

James LeClair
James LeClair

Reputation: 1294

assuming this is a rudimentary representation of the data you are passing in (forgive the assumptions if they are wrong)

-var keys = {global: {faq: 'faq'}, tax:{'faq_a1': 'a', 'faq_a2': 'b', 'faq_a3':'c', 'faq_a4': 'd'}}

This will work:

-for(var i=1; i<5; i++)
   -var taxId = '#tax-' + i;
   -var keyId = 'faq_a' + i;
   div.tile_content.tile_tax_form_bottom_bar
      h3.form_headline!= keys.global.faq
      div#tax.panel-group.custom-panel
         div.panel.panel-default
            div.panel-heading
               h4.panel-title
                  a.collapsed(href=taxId, data-toggle='collapse', data-parent='#tax')
                     i.fa.fa-times-circle
                     i.fa.fa-plus-circle
                     != keys.tax.faq_q1
            div.panel-collapse.collapse(id=taxId)
               div.panel-body
                  p!= keys.tax[keyId]

if you don't want to declare the variables up top you can try to interpolate, its a matter of taste. I think it looks cleaner without the interpolation.

I ran this locally and it built to what you are describing. I'd paste the output, but its a lot of lines.

Upvotes: 1

Related Questions