我有以下场景:
- 我们正在使用 web2py在服务器端
- 我们正在提供一些 ember.js页数
- 目前那些 ember.js 页面在 iframe 中,因为 ember.js and web2py conflict with template {{ }} marks .这意味着我们不能轻易混合使用 web2py 模板和 ember.js 模板。
- 所以我实现了辅助类解决方案:
class em(DIV)
- 现在我想处理带有 ember 标记的原始 html 文件,并生成 em 标记 文件,将 ember.js 和 web2py 模板系统集成到一个内聚单元中。
为此,我需要将 ember.js 文件中 {{XXX}}
的所有实例更改为 {{=em('XXX')}},包括 跨越多行的实例。我正在考虑在这里使用正则表达式,但我想避免重新发明轮子(并且不得不处理奇怪的极端情况)
你能想到在 python 中解析这些模板的通用方法吗?只需寻找开始和结束分隔符({{
和 }}
),然后放入 =em('XXX')
、处理换行符,以及保持格式(即,如果有的话,保留换行符)。
注意:这实际上不是 ember.js 特定的;它可以应用于任何基于多行定界符的模板系统。
最佳答案
请注意,在 web2py 的主干版本中(将在未来几天作为 web2py 2.0 发布),您现在可以为模板指定自定义分隔符——这样您就可以更改 web2py 分隔符,这样它们就不再与ember.js 分隔符。例如,在模型文件中:
response.delimiters = ['{%', '%}']
然后在您的 web2py 模板中,您可以:
{%=P('hello world')%}
<p>{{ember template code}}</p>
{%=P('{{ember template code generated by web2py}}')%}
这将产生:
<p>hello world</p>
<p>{{ember template code}}</p>
<p>{{ember template code generated by web2py}}</p>
请注意,response.delimiters 是在每个请求上设置的,因此如果您不想更改所有页面上的 web2py 分隔符,而只想更改那些包含 ember 代码的页面,您可以有条件地设置 response.delimiters(通过将其设置为需要它的特定操作,或通过检查请求的 Controller 和/或模型文件中的函数)。例如,在模型文件中:
if request.function in ['action1', 'action2', 'action3']:
response.delimiters = ['{%', '%}']
或在 Controller 中:
def action1():
response.delimiters = ['{%', '%}']
[etc.]
关于python - 使用 python 处理 ember.js 标记的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12128593/