问题
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