karzol73
karzol73

Reputation: 75

Jade/Pug w/ HTML data element

I use the following line in my code with success:

.div(data-text='text')

but I am working on a multilingual site reading the languages w/JQuery from JSON. In this case, the usual way to put the text into a simple HTML p tag is:

p(tkey='text')

I would like to use the same method in the data-text div:

.div(data-text=(tkey='text'))

The problem is probably caused by the fact that I wanted to use it within a loop such as:

- for(var i = 1; i < 5; i++) {
    .div(data-text='data' + i)
- }

Is it possible? What is the syntax?

Thank you for all!

Upvotes: 0

Views: 118

Answers (1)

Graham
Graham

Reputation: 7802

Pug has a few constructs to loop, docs are here.

To do what you want I'd suggest using each:

each val in [1, 2, 3, 4, 5]
  div(data-text= 'data' + val)

An alias of each is for so this does the same thing:

for val in [1, 2, 3, 4, 5]
  div(data-text= 'data' + val)

If you have a larger number of values to iterate through then shift to the while syntax:

- var index = 0;
- var limit = 25;
while index < limit
    div(data-text= 'data' + index++)

However, you're usually looping through an existing array of objects such as a result set from a database. If you want to use the index in the each loop then add that as the second argument:

- var results = ["Adam", "Bonnie", "Clara"];
each person, index in results
  p(data-text= 'data' + index)= person

Will produce this HTML:

<p data-text='data1'>Adam</p>
<p data-text='data2'>Bonnie</p>
<p data-text='data3'>Clara</p>

Also note that .div creates this HTML:

<div class="div"></div>

If you only want a div then leave out the leading period, div produces this:

<div></div>

Upvotes: 1

Related Questions