yield() 函数允许您在函数调用范围内编写额外的 Tritium 代码。
例如,您可以像这样使用wrap() 函数:
wrap("div") {
add_class("product")
}
在此示例中,wrap() 函数将当前节点包围在 <div> 标记内,然后将“产品”类添加到该标记,从而生成以下 HTML:
<div class="product">
<!-- the node you originally selected is now wrapped inside here -->
</div>
对add_class() 的函数调用正在wrap() 函数的yield() 块内执行。 wrap() function definition 看起来像这样:
@func XMLNode.wrap(Text %tag) {
%parent_node = this()
insert_at(position("before"), %tag) {
move(%parent_node, this(), position("top"))
yield()
}
}
如您所见,wrap() 的函数定义中的 yield() 调用让 Tritium 代码让执行我上面编写的 add_class() 函数。
所以再次使用我的例子,这段代码:
wrap("div") {
add_class("product")
}
和写作一模一样:
%parent_node = this()
insert_at(position("before"), "div") {
move(%parent_node, this(), position("top"))
add_class("product") ## <-- This is where the code inside a yield() block gets added
}