插入玉和Python字典

时间:2013-11-05 23:13:35

标签: python pug pyjade

鉴于玉石模板和字典,如何使用字典填充玉石模板?例如,

>>> data = {
...   'name': "World",
...   'ages': [10, 20, 30]
... }

>>> template = """
... html
...   body
...     h1 "Hello, #{name}!"
...     each age in ages
...        h3 "Age: #{age}"
... """

>>> print interpolate(template, data)
<html>
  <body>
    <h1>Hello, World!</h1>
    <h3>Age: 10</h2>
    <h3>Age: 20</h2>
    <h3>Age: 30</h2>
  </body>
</html>

我一直在关注pyjade,但我无法弄清楚像interpolate这样的函数的定义。我该如何撰写interpolate

1 个答案:

答案 0 :(得分:1)

pyjade没有为您提供直接插入jade和python对象的选项;相反,它允许将玉转换为对另一个模板引擎友好的格式,例如Jinja2。然后,此模板引擎可以为您执行插值。例如,

data = {
  'name': "World",
  'ages': [10, 20, 30]
}

template = """
div
  h1 "Hello, #{name}!"
  each age in ages
     h3 "Age: #{age}"
"""

def interpolate(template, data):
  import os
  from jinja2 import Environment

  env = Environment(
      loader     = FileSystemLoader(os.getcwd()),
      extensions = ['pyjade.ext.jinja.PyJadeExtension']
  )

  # write template to disk (there's probably a way around this?)
  with open("templates/template.jade", "w") as f:
    f.write(template.strip())

  return (
    env
    .get_template("templates/template.jade")
    .render(data)
  )

print interpolate(template, data)
# <div>
#   <h1>"Hello, World!"</h1>
#   <h3>"Age: 10"</h3>
#   <h3>"Age: 20"</h3>
#   <h3>"Age: 30"</h3>
# </div>