PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, June 28, 2022

[FIXED] How do you increment an assigned variable in smarty without displaying it

 June 28, 2022     php, smarty     No comments   

Issue

So I have an assigned variable in smarty:

{assign var=number value=0}

Now I can increment it using

{$number++}

or

{++$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.


Solution

You could do this:

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

The above will be compiled to:

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

or

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

Which in turn will be compiled as:

$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']);
   }
}

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

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



Answered By - Cyclonecode
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing