Skip to content Skip to sidebar Skip to footer

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)= labe

Solution 1:

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 idxfor 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)

Solution 2:

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

Solution 3:

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)

Solution 4:

you can do that with pypugjs (successor of pyjade)

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

Post a Comment for "Using Python Code In Pyjade"