如何在Smarty中递增分配的变量而不显示它 [英] How do you increment an assigned variable in smarty without displaying it

查看:91
本文介绍了如何在Smarty中递增分配的变量而不显示它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在smarty中分配了一个变量:

So I have an assigned variable in smarty:

{assign var=number value=0}

现在我可以使用

{$number++}

{++$number}

这正是我所需要的,唯一的问题是,它在页面上显示$ number的值. 有什么方法可以增加值但不显示?

Which is exactly what I need, only problem is, it displays the value of $number on the page. Is there a way I can increment the value but not display it?

这不在循环内使用,否则我会使用诸如迭代或索引之类的东西.

This is not used inside of a loop otherwise I would use something like iteration or index.

推荐答案

您可以执行以下操作:

{assign var=val value=1}
{assign var=val value=$val+1}
{$val} // displays 2

以上内容将编译为:

$this->assign('val', 1);
$this->assign('val', $this->_tpl_vars['val']+1);
echo $this->_tpl_vars['val'];

{assign var=var value=1}
{capture assign=var}{$var+1}{/capture}
{$var} // displays 2

依次将其编译为:

$this->assign('var', 1);
ob_start();
echo $this->_tpl_vars['var']+1;
$this->_smarty_vars['capture']['default'] = ob_get_contents();
$this->assign('var', ob_get_contents());
ob_end_clean();
echo $this->_tpl_vars['var'];

另一种方法是编写一个小插件:

another approach would be to write a small plugin:

// plugins/function.inc.php
function smarty_function_inc($params, Smarty &$smarty)
{
   $params['step'] = empty($params['step']) ? 1 : intval($params['step']);

   if (empty($params['var'])) {
      trigger_error("inc: missing 'var' parameter");
      return;
   }
   if (!in_array($params['var'], array_keys($smarty->_tpl_vars))) {
      trigger_error("inc: trying to increment unassigned variable ".$params['var']);
      return;
   }
   if (isset($smarty->_tpl_vars[$params['var']])) {
      $smarty->assign($params['var'],
      $smarty->_tpl_vars[$params['var']] + $params['step']);
   }
}

然后将像这样调用该函数,请注意step是可选的,如果未指定,则变量将加一:

The function would then be called like this, notice that step is optional and if not given the variable will be incremented by one:

{assign var=var value=0}
{inc var=var step=2}
{$var} // displays 2

参考
聪明{assign}
聪明{capture}
使用插件扩展Smarty

Reference
Smarty {assign}
Smarty {capture}
Extending Smarty With Plugins

这篇关于如何在Smarty中递增分配的变量而不显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆