{block}

{block}可在模板上定义一块区域,以进行模板继承。详细参见模板继承.

子模板中的{block}区域代码,将会替换父模板对应的区域代码。

另外,{block}可以设置成合并父子模板的相应区域。在子模板的{block}中定义 appendprepend,可以使子模板附加在父模板 {block}区域的后面或前面。 在{block}内容中使用{$smarty.block.parent},可以让父模板的区域代码放到 子模板{block}内的任何位置。

{blocks}可以嵌套使用。

属性:

参数名称 类型 必选参数 默认值 说明
name string Yes n/a 模板区域的名称

可选属性 (仅在子模板中使用):

名称 说明
append {block}区域代码将附加到父模板的{block}内容之后
prepend {block}区域代码将附加到父模板的{block}内容之前
hide 在没有该名称区域的时候,忽略区域内容。
nocache 关闭{block} 缓存


Example 7.15. 简单的 {block} 例子

parent.tpl

  1. <html>
  2. <head>
  3. <title>{block name="title"}Default Title{/block}</title>
  4. <title>{block "title"}Default Title{/block}</title> {* short-hand *}
  5. </head>
  6. </html>
  7.  

child.tpl

  1. {extends file="parent.tpl"}
  2. {block name="title"}
  3. Page Title
  4. {/block}
  5.  

结果输出:

  1. <html>
  2. <head>
  3. <title>Page Title</title>
  4. </head>
  5. </html>
  6.  


Example 7.16. 前面附加 {block} 例子

parent.tpl

  1. <html>
  2. <head>
  3. <title>{block name="title"}Title - {/block}</title>
  4. </head>
  5. </html>
  6.  

child.tpl

  1. {extends file="parent.tpl"}
  2. {block name="title" prepend}
  3. Page Title
  4. {/block}
  5.  

结果输出

  1. <html>
  2. <head>
  3. <title>Title - Page Title</title>
  4. </head>
  5. </html>
  6.  


Example 7.17. 后面附加 {block} 例子

parent.tpl

  1. <html>
  2. <head>
  3. <title>{block name="title"} is my title{/block}</title>
  4. </head>
  5. </html>
  6.  

child.tpl

  1. {extends file="parent.tpl"}
  2. {block name="title" append}
  3. Page Title
  4. {/block}
  5.  

结果输出:

  1. <html>
  2. <head>
  3. <title>Page title is my titel</title>
  4. </head>
  5. </html>
  6.  


Example 7.18. {$smarty.block.child} 例子

parent.tpl

  1. <html>
  2. <head>
  3. <title>{block name="title"}The {$smarty.block.child} was inserted here{/block}</title>
  4. </head>
  5. </html>
  6.  

child.tpl

  1. {extends file="parent.tpl"}
  2. {block name="title"}
  3. Child Title
  4. {/block}
  5.  

结果输出:

  1. <html>
  2. <head>
  3. <title>The Child Title was inserted here</title>
  4. </head>
  5. </html>
  6.  


Example 7.19. {$smarty.block.parent} 例子

parent.tpl

  1. <html>
  2. <head>
  3. <title>{block name="title"}Parent Title{/block}</title>
  4. </head>
  5. </html>
  6.  

child.tpl

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

结果输出:

  1. <html>
  2. <head>
  3. <title>You will see now - Parent Title - here</title>
  4. </head>
  5. </html>
  6.  

参见 模板继承, $smarty.block.parent, $smarty.block.child, 和 {extends}

原文: https://www.smarty.net/docs/zh_CN/language.function.block.tpl