How to template like ERB in Python? [closed]

Deadly 提交于 2020-06-25 10:40:09

问题


ERB, if you're not familiar with it, is the templating language used by Ruby On Rails and many other Ruby projects. In short, it allows you to evaluate raw ruby code inside HTML templates and render the result.

Consider the following:

#hello.erb
<html>
<body>
  <p>Hello, <%= @name %></p>
</body>
<html>

The Ruby instance variable @name would get replaced and rendered out onto the page seen by users.

Now, Python has a common templating language known as Jinja2 which works in almost the same way (mostly using {{ }}s instead of <% %>s), but there's one massive difference between the two:

ERB allows you to use any valid Ruby code, while Jinja2 only has a very limited subset of Python-esque language, but not raw Python.

The question:

How do you template HTML with Python, using the entire language, rather than a limited subset?


回答1:


Mako allows to write a regular block of Python code, like this

this is a template
<%
    x = db.get_resource('foo')
    y = [z.element for z in x if x.frobnizzle==5]
%>
% for elem in y:
    element: ${elem}
% endfor

http://docs.makotemplates.org/en/latest/syntax.html#python-blocks



来源:https://stackoverflow.com/questions/35104228/how-to-template-like-erb-in-python

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