Language function block

{block}标签用于定义模板源代码中的命名区域,用于模板继承。通过模板继承,子模板中的{block}模板源区域将替换父模板中对应的区域。

以下是{block}标签的属性:

  • name(必需):指定模板源代码区域的名称。
  • assign(可选):指定将该区域的输出赋值给的变量名称。

{block}标签还具有一些选项标志:

  • append:将子模板中的{block}内容追加到父模板{block}内容之后。
  • prepend:将子模板中的{block}内容追加到父模板{block}内容之前。
  • hide:如果不存在同名的子模板{block},则忽略该{block}内容。
  • nocache:禁用{block}内容的缓存。

在子模板中,可以使用{$smarty.block.parent}来插入父模板的{block}内容,使用{$smarty.block.child}来插入子模板的{block}内容。

下面是一些示例:

parent.tpl

<html>
  <head>
    <title>{block name="title"}Default Title{/block}</title>
    <title>{block "title"}Default Title{/block}</title>  {* 简写形式 *}
  </head>
</html>
child.tpl

{extends file="parent.tpl"}
{block name="title"}
Page Title
{/block}

结果将如下所示:

<html>
  <head>
    <title>Page Title</title>
  </head>
</html>
parent.tpl

<html>
  <head>
    <title>{block name="title"}Title - {/block}</title>
  </head>
</html>
child.tpl

{extends file="parent.tpl"}
{block name="title" append}
    Page Title
{/block}

结果将如下所示:

<html>
  <head>
    <title>Title - Page Title</title>
  </head>
</html>
parent.tpl

<html>
  <head>
    <title>{block name="title"} is my title{/block}</title>
  </head>
</html>
child.tpl

{extends file="parent.tpl"}
{block name="title" prepend}
Page Title
{/block}

结果将如下所示:

<html>
  <head>
    <title>Page title is my title</title>
  </head>
</html>
parent.tpl

<html>
  <head>
    <title>{block name="title"}The {$smarty.block.child} was inserted here{/block}</title>
  </head>
</html>
child.tpl

{extends file="parent.tpl"}
{block name="title"}
    Child Title
{/block}

结果将如下所示:

<html>
  <head>
    <title>The Child Title was inserted here</title>
  </head>
</html>
parent.tpl

<html>
  <head>
    <title>{block name="title"}Parent Title{/block}</title>
  </head>
</html>
child.tpl

{extends file="parent.tpl"}
{block name="title"}
    You will see now - {$smarty.block.parent} - here
{/block}

结果将如下所示:

<html>
  <head>
    <title>You will see now - Parent Title - here</title>
  </head>
</html>

请参阅以下链接获取更多关于 Smarty 模板引擎中{block}标签和相关内容的信息: