如何在Python中像ERB一样做模板? [英] How to template like ERB in Python?

查看:104
本文介绍了如何在Python中像ERB一样做模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ERB ,如果您对它不熟悉的是Ruby On Rails和许多其他Ruby项目使用的模板语言.简而言之,它允许您评估HTML模板中的原始红宝石代码并呈现结果.

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.

请考虑以下内容:

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

Ruby实例变量@name将被替换并呈现到用户看到的页面上.

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

现在,Python具有一种称为 Jinja2 的通用模板语言,其工作方式几乎相同(大部分使用{{ }} s而不是<% %> s),但两者之间有一个巨大的区别:

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允许您使用任何有效的Ruby代码,而Jinja2仅具有非常有限的Python式语言子集,而没有原始Python.

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.

如何使用Python(而不是有限的子集)使用HTML来模板化HTML?

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

推荐答案

Mako 允许编写常规的Python代码块,例如这个

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 -块

这篇关于如何在Python中像ERB一样做模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆