跳至内容

{block}

{block} 用于定义模板继承的模板源名称区域。有关详情,请参阅 模板继承 的部分。

子模板的 {block} 模板源区域将替换父模板中对应的区域。

还可以合并子模板和父模板的 {block} 区域。您可以使用子块 {block} 定义的 appendprepend 选项标记来附加或前置父 {block} 内容。使用 {$smarty.block.parent} 可以在子 {block} 内容的任何位置插入父模板的 {block} 内容。{$smarty.block.child} 在父 {block} 的任何位置插入子模板的 {block} 内容。

{blocks} 可以嵌套。

属性

属性名称 必需 说明
name 模板源块的名称
assign 将块输出分配到的变量的名称。

注意

assign 属性仅适用于实际执行的块,因此您可能还需要将它添加到每个子块中。

(仅在子模板中)选项标记

名称 说明
append {block} 内容将附加到父模板 {block} 的内容
prepend {block} 内容将前置到父模板 {block} 的内容
hide 如果没有同名子块,则忽略块内容。
不可缓存 禁用缓存 {block} 内容

示例

parent.tpl

    <html>
      <head>
        <title>{block name="title"}Default Title{/block}</title>
        <title>{block "title"}Default Title{/block}</title>  {* short-hand  *}
      </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 titel</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.parent$smarty.block.child以及{extends}