什么是 Smarty?
为什么使用它?
使用案例和工作流程
语法比较
模板继承
最佳实践
速成课程
{block} 用来定义一个模板源中供模板继承的命名区域。详情请参阅 模板继承 一节。
{block} 子模板的模板源区域将替换父模板中的对应区域。
此外,还可以合并子模板和父模板的 {block} 区域。您可以通过在子 {block} 定义中使用 append 或 prepend 选项标记来追加或前置父 {block} 内容。通过使用 {$smarty.block.parent},可以将父模板的 {block} 内容插入子 {block} 内容的任意位置。{$smarty.block.child} 会将子模板的 {block} 内容插入父 {block} 的任意位置。
{blocks} 可以嵌套。
属性
| 属性名 | 类型 | 必需 | 默认值 | 说明 |
|---|---|---|---|---|
| name | 字符串 | 是 | n/a | 模板源块的名称 |
选项标记(仅子模板中使用)
| 名称 | 说明 |
|---|---|
| 追加 | 将 {block} 内容追加到父模板 {block} 的内容 |
| 前置 | 将 {block} 内容前置到父模板 {block} 的内容 |
| 隐藏 | 如果不存在同名子块的内容,则忽略块内容。 |
| 不缓存 | 禁用 {block} 内容的缓存 |
示例 7.15。简单的 {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>
示例 7.16。前置 {block} 示例
parent.tpl
<html>
<head>
<title>{block name="title"}Title - {/block}</title>
</head>
</html>
child.tpl
{extends file="parent.tpl"}
{block name="title" prepend}
Page Title
{/block}
结果如下所示
<html>
<head>
<title>Title - Page Title</title>
</head>
</html>
示例 7.17。追加 {block} 示例
parent.tpl
<html>
<head>
<title>{block name="title"} is my title{/block}</title>
</head>
</html>
child.tpl
{extends file="parent.tpl"}
{block name="title" append}
Page Title
{/block}
结果如下所示
<html>
<head>
<title>Page title is my titel</title>
</head>
</html>
示例 7.18。{$smarty.block.child} 示例
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>
示例 7.19。{$smarty.block.parent} 示例
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>