Using python code in pyjade

核能气质少年 提交于 2020-01-03 16:48:21

问题


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?


回答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 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)




回答2:


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




回答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)



回答4:


you can do that with pypugjs (successor of pyjade)

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


来源:https://stackoverflow.com/questions/15779120/using-python-code-in-pyjade

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!