是否可以在Mako中创建新标记?

2024-05-23 13:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

mako新手,在文件中没有发现。。。在

我想做的一件事是:

<%mytag n=12>
blabla ${x}
</%mytag>

其工作原理如下:

如果X[n](这里,X[12])变量是int或字符串,则使用x = X[12]
=>;使用X[12] = 23,它将呈现:blabla 23

否则,如果X[n]是一个列表,则执行for循环,为x in X[n]
=>;使用X[12] = [1, 2, 'bla'],它将呈现:

^{pr2}$

请尝试回答主要问题(是否可以自定义标记?)如果可能,在给出我想做的事情的建议之前,谢谢:)


Tags: 文件字符串in标记gt列表formako
1条回答
网友
1楼 · 发布于 2024-05-23 13:22:06

"namespaces"文档似乎描述了您的目标,特别是:

Namespaces can also import regular Python functions from modules. These callables need to take at least one argument, context, an instance of Context. A module file some/module.py might contain the callable:

def my_tag(context):
    context.write("hello world")
    return ''

A template can use this module via:

<%namespace name="hw" module="some.module"/>

${hw.my_tag()}

…和:

The "custom tag" format is intended mainly for namespace functions which recognize body content, which in Mako is known as a “def with embedded content”:

<%mynamespace:somefunction arg1="some argument" args="x, y">
    Some record: ${x}, ${y}
</%mynamespace:somefunction>

相关问题 更多 >