[英]Add custom tokens in Jinja2 (e.g. %% somevar %%)
I'm making a Flask app for local development (on a Mac) of HTML templates that will eventually be served through ASP.NET.我正在制作 Flask 应用程序,用于 HTML 模板的本地开发(在 Mac 上),最终将通过 ASP.NET 提供服务。
For the purposes of local development, I want a way to replace the contents of .NET-style tokens with some data, meaning that Jinja2 would need to be able to recognize %%... %%
tokens in addition to the standard ones: {{... }}
, <%... %>
, etc.出于本地开发的目的,我想要一种方法用一些数据替换 .NET 样式标记的内容,这意味着 Jinja2 除了标准标记之外,还需要能够识别
%%... %%
标记: {{... }}
, <%... %>
等。
Everything I've found online pertains to the inclusion of some new functionality within the existing tags (eg {{ my_custom_function | arg1 arg2 }}
)我在网上找到的所有内容都与在现有标签中包含一些新功能有关(例如
{{ my_custom_function | arg1 arg2 }}
)
But what about defining a new pattern for tags altogether?但是,如何为标签完全定义一个新模式呢? Has anyone done this successfully?
有没有人成功做到这一点? And will it require modification to the Jinja2 core?
是否需要对 Jinja2 内核进行修改?
As far as I know, you can use one set for block_start_string
and block_end_string
, as well as one set for variable_start_string
and variable_end_string
. 据我所知,你可以使用一组用于
block_start_string
和block_end_string
,以及一组用于variable_start_string
和variable_end_string
。
From jinja2/environment.py 来自jinja2 / environment.py
`block_start_string`
The string marking the begin of a block. Defaults to ``'{%'``.
`block_end_string`
The string marking the end of a block. Defaults to ``'%}'``.
`variable_start_string`
The string marking the begin of a print statement.
Defaults to ``'{{'``.
`variable_end_string`
The string marking the end of a print statement. Defaults to
``'}}'``.
You can override these with environment variables. 您可以使用环境变量覆盖这些。 Though, I don't think there is a way to have multiple types recognized.
虽然,我认为没有办法让多种类型得到认可。 For instance, you can't have
{{
and <%
both work, but with a little hackery you certainly could. 例如,你不能
{{
和<%
都工作,但有一点hackery你当然可以。
In addition to the correct answer maybe an example implementation to change the variable marker:除了正确答案之外,还可能是更改变量标记的示例实现:
Add following header to the first line in the jinja2 template file.将以下 header 添加到 jinja2 模板文件的第一行。
#jinja2: variable_start_string: "#{" , variable_end_string: "}#"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.