跳至内容

{eval}

{eval} 用于将变量作为模板进行评估。可用于将模板标签或变量嵌入变量,或者将标签或变量嵌入配置文件变量中。

属性

属性名称 必需 描述
var 要评估的变量(或字符串)
assign 将输出分配给的模板变量

如果指定了 assign 属性,则 {eval} 函数的输出将分配给该模板变量,而不是输出到模板。

注意

  • 评估过的变量与模板同等对待。它们遵循相同的转义和安全功能,就像它们是模板一样。

  • 评估变量在每次调用时都进行编译,编译版本不会保存!但是,如果启用了 缓存,则输出会与模板的其他部分一起缓存。

  • 如果要评估的内容不经常更改,或者被反复使用,则考虑使用 {include file="string:{$template_code}"} 来代替。这可能会缓存已编译的状态,因此无需在每次调用时都运行(相对较慢的)编译器。

示例

配置文件 setup.conf 的内容。

emphstart = <strong>
emphend = </strong>
title = Welcome to {$company}'s home page!
ErrorCity = You must supply a {#emphstart#}city{#emphend#}.
ErrorState = You must supply a {#emphstart#}state{#emphend#}.

模板所在的位置

{config_load file='setup.conf'}

{eval var=$foo}
{eval var=#title#}
{eval var=#ErrorCity#}
{eval var=#ErrorState# assign='state_error'}
{$state_error}

上面这个模板将输出

This is the contents of foo.
Welcome to Foobar Pub & Grill's home page!
You must supply a <strong>city</strong>.
You must supply a <strong>state</strong>.

这会输出服务器名称(大写)和 IP。已分配的变量 $str 可能来自数据库查询。

<?php
    $str = 'The server name is {$smarty.server.SERVER_NAME|upper} '
           .'at {$smarty.server.SERVER_ADDR}';
    $smarty->assign('foo',$str);

模板所在的位置

{eval var=$foo}