传递标题到头部模板

当你的模板多数使用了相同的头部和底部HTML代码,通常 会将它们分隔到单独的模板中,用 {include}来载入它们。但如果头部HTML会根据页面的不同,而需要有不同的标题,那么你需要在包含模板时设置标题为属性


Example 21.3. 传递标题到头部模板

mainpage.tpl - 当主体页面被渲染时,“Main Page”的标题值会被传递到header.tpl,这样就可以被当作标题使用了。

  1. {include file='header.tpl' title='Main Page'}
  2. {* template body goes here *}
  3. {include file='footer.tpl'}
  4.  

archives.tpl - 当主体页面被渲染时,页面标题会是“Archives”。注意在下面例子中,我们使用了来自配置文件archives_page.conf的变量,替代硬编码的变量值。

  1. {config_load file='archive_page.conf'}
  2.  
  3. {include file='header.tpl' title=#archivePageTitle#}
  4. {* template body goes here *}
  5. {include file='footer.tpl'}
  6.  

header.tpl - 注意下面例子使用了default的变量修饰器,当标题$title变量未设置时,将显示“Smarty News”。

  1. <html>
  2. <head>
  3. <title>{$title|default:'Smarty News'}</title>
  4. </head>
  5. <body>
  6.  

footer.tpl

  1. </body>
  2. </html>
  3.  

原文: https://www.smarty.net/docs/zh_CN/tips.passing.vars.tpl