Chung Wu
Chung Wu

Reputation: 2417

Using python code in pyjade

I'm trying to generate a list using pyjade, like so:

ul
  - for i, (label, link) in enumerate(tabs)
    li(class="selected" if i == selected_index else "")
      a(href=link)= label

But I see this error:

UndefinedError: 'enumerate' is undefined

I must be embedding python code into Jade wrong. What's the right way to do this?

Upvotes: 4

Views: 2785

Answers (4)

Andy
Andy

Reputation: 786

you can do that with pypugjs (successor of pyjade)

li(class=("selected" if i == selected_index else ""))

Upvotes: 1

JelteF
JelteF

Reputation: 3271

You should use the way of adding functions to the templating environment that is used by the tamplate language you compile the jade files to using pyjade.

For Flask using jinja this should be put in your __init__.py would be:

app.jinja_env.globals.update(enumerate=enumerate)

Upvotes: 1

Brian
Brian

Reputation: 555

Jade uses what I refer to as "implicit enumeration" - it enumerates values in a list simply by adding one more variable, i, than there are values to unpack: for item, i in list_like (For dicts you can do for key, val in dict_like)

Shown below is your example using tuple unpacking and "implicit enumeration" together, tested with PyJade 2.0.2

- var selected_index = 0
- var tabs = [('hello', '/world'), ('citizens', '/please/respect_your_mother'), ('thank_you', '/bye')]
ul
    // unpack `tabs` and tack on the variable `i` to hold the current idx
    for label, link, i in tabs
        li(class="selected" if (i == selected_index) else "")
            a(href="#{link}") #{label}

NOTE: As more commonly seen in "standard" Jade code, as of this writing, PyJade does NOT support the ternary operator for assignment. (variable= (condition)? value_if_true : value_if_false)

Upvotes: 4

Chung Wu
Chung Wu

Reputation: 2417

No; pyjade does not allow embedding arbitrary python code into jade. Use jade's syntax instead.

Upvotes: 1

Related Questions