如何检查是否已分配Smarty变量?

时间:2021-08-02 20:36:33

How do I check to see if a particular value has already been assigned to Smarty and if not assign a (default) value?

如何检查特定值是否已分配给Smarty,如果没有分配(默认)值?

Answer:

if ($this->cismarty->get_template_vars('test') === null) {
   $this->cismarty->assign('test', 'Default value');
}

3 个解决方案

#1


14  

Smarty 2

if ($smarty->get_template_vars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}

Smarty 3

if ($smarty->getTemplateVars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}

Note that for Smarty 3, you will have to use $smarty->getTemplateVars instead.

请注意,对于Smarty 3,您必须使用$ smarty-> getTemplateVars。

#2


1  

get_template_vars() will return null if you haven't set a variable, so you can do

如果你没有设置变量,get_template_vars()将返回null,所以你可以这样做

if ($smarty->get_template_vars('test') === null) {
    echo "'test' is not assigned or is null";
}

However that check will fail if you have a variable assigned but set as null, in which case you could do

但是,如果您已分配变量但设置为null,则该检查将失败,在这种情况下您可以执行此操作

$tmp = $smarty->get_template_vars();
if (!array_key_exists('test', $tmp)) {
    echo "'test' is not assigned";
}

#3


0  

Pretty sure you can do:

很确定你能做到:

if (!isset($smarty['foo'])) 
{
    $smarty->assign('foo', 'some value');
}

#1


14  

Smarty 2

if ($smarty->get_template_vars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}

Smarty 3

if ($smarty->getTemplateVars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}

Note that for Smarty 3, you will have to use $smarty->getTemplateVars instead.

请注意,对于Smarty 3,您必须使用$ smarty-> getTemplateVars。

#2


1  

get_template_vars() will return null if you haven't set a variable, so you can do

如果你没有设置变量,get_template_vars()将返回null,所以你可以这样做

if ($smarty->get_template_vars('test') === null) {
    echo "'test' is not assigned or is null";
}

However that check will fail if you have a variable assigned but set as null, in which case you could do

但是,如果您已分配变量但设置为null,则该检查将失败,在这种情况下您可以执行此操作

$tmp = $smarty->get_template_vars();
if (!array_key_exists('test', $tmp)) {
    echo "'test' is not assigned";
}

#3


0  

Pretty sure you can do:

很确定你能做到:

if (!isset($smarty['foo'])) 
{
    $smarty->assign('foo', 'some value');
}