php: smarty assign content plugin

January 12, 2009 in Smarty

I needed to assign a block of content to a variable instead of just a value.. so i set about creating this plugin

function smarty_block_assign_content($params, $content, &$smarty)
{
        $smarty = clone($smarty); //Copy the original class, so there's no garbage variables after we finish
        if(!isset($content))
                return;
        if (!isset($params['var'])) {
                $smarty->trigger_error("assign_content: missing 'var' parameter", E_USER_WARNING);
                return;
        }

        //Compile content to ensure all smarty tags get processed
        $smarty->assign($params['var'], $content);
                $smarty->assign($k, $v);
        return ;
}

example of usage:

{assign_content var='menu'}
  {foreach from=$menus.cats->children item='cat'}
  <div class="item{if $cat->active || $cat->expanded}_select{/if}">
    <div class="arrow"></div>
    {if !$cat->active}<a href="{$cat->link}">{/if}{$cat->text}{if !$cat->active}</a>
    {/if}
  </div>
  {if $cat->children|@count ne 0 || $cat->expanded}
    {foreach from=$cat->children item='subCat'}
      <div class="subitem{if $subCat->active}_select{/if}">
        <div class="arrow"></div>
      {if !$subCat->active}<a href="{$subCat->link}">{/if}{$subCat->text}{if !$subCat->active}</a>{/if}
      </div>
    {/foreach}
  {/if}
  {/foreach}
{/assign_content}

This will set the code we used to generate the menu and assign it to $menu for later use.
Hope you find as usefull