Smarty Forum Index Smarty
The discussions here are for Smarty, a template engine for the PHP programming language.

populate an associative array in tpl

 
Post new topic   Reply to topic    Smarty Forum Index -> Smarty Development
View previous topic :: View next topic  
Author Message
bqh19
Smarty n00b


Joined: 21 Apr 2003
Posts: 2

PostPosted: Mon Apr 21, 2003 10:41 pm    Post subject: populate an associative array in tpl Reply with quote

Is there any body can help me to populate the following associative array in the tpl:
$catelog=array('Men'=>array('Out Wear','Knitwear','Sports Wear'), 'Women'=>array('Out Wear','Knitwear','Sports wear'), 'Kids'=>array('Knit wear','Sports wear'));

Thank you very much for your help!

Brian
Back to top
View user's profile Send private message
dthought
Smarty Regular


Joined: 21 Apr 2003
Posts: 55
Location: Melbourne, Australia

PostPosted: Mon Apr 21, 2003 11:29 pm    Post subject: Reply with quote

Forgive me if I'm wrong, but isn't that a task for PHP code? I always thought Smarty was more geared towards the displaying of information as opposed to its creation...
Back to top
View user's profile Send private message Visit poster's website
messju
Administrator


Joined: 16 Apr 2003
Posts: 3336
Location: Oldenburg, Germany

PostPosted: Mon Apr 21, 2003 11:43 pm    Post subject: Reply with quote

if you mean with "populate" to display:

Code:

(assuming you did $smarty->assing('catelog', $catelog); in php )

{foreach name=cat from=$catelog key=cat item=subcat_array}
  Categorie #{$smarty.foreach.cat.iteration} {$cat}
  {foreach name=subcat from=$catelog.$cat item=subcat}
    Subcategorie #{$smarty.foreach.subcat.iteration} {$subcat}
  {/foreach}
{/foreach}


if you mean by "populate" to assign:

no. dthought is right.
Back to top
View user's profile Send private message Send e-mail Visit poster's website
boots
Administrator


Joined: 16 Apr 2003
Posts: 5611
Location: Toronto, Canada

PostPosted: Tue Apr 22, 2003 12:43 am    Post subject: Reply with quote

dthought is right, IMHO, but if you really want to slow things down, here is some rope for you.

Basically, I tore out a small piece of my data handlers and put it into a smarty block function with a pretty quick-and-dirty parser. Well, dirty for sure.

Before the flames begin--I'm posting this only to show the user who asked that it can be done, even if it is discouraged. Wink

Hope it helps.

Place the following code into your plugins directory:

block.dsrlz.php

Code:
<?php

/**
* Smarty block plugin
* -------------------------------------------------------------
* Type:     block
* Name:     dsrlz
* Version:  1.1
* Author:   boots
* Purpose:  make assignnents from within a template with a simple syntax
*           supporting multiple assignments and allowing for simple
*           assignments as well as arrays and keyed arrays.
* See:      http://www.phpinsider.com/smarty-forum/viewtopic.php?t=64
*
* Example:
* {dsrlz}
* test: "test"
* test2: 10
* test3: "this is a test"
*
* test4: ["test1", "test2", "test3"]
* test5: [
*       key1: "value1"
*       key2: "value2"
* ]
* test6: [
*       key1: "value1"
*       key2: [
*          subkey1: "subvalue1"
*          subkey2: "subvalue2"
*       ]
* ]
* {/dsrlz}
*
* creates the following smarty assignments:
* $test  [= "test"]
* $test2  [= 10]
* $test3  [= "this is a test"]
* $test4  [= array("test1", "test2", "test3")]
* $test5  [= array('key1'=>"value1", 'key2'=>"value2")]
* $test6  [= array('key1'=>"value1", 'key2'=>array('subkey1'=>"subvalue1", 'subkey2'=>"subvalue2"))]
*/
function smarty_block_dsrlz($params, $content, &$smarty)
{
    if (!empty($content)) {
        $src = $content;

        // pre-tokenize strings
        $src_c  = preg_match_all(   '/(".*")/',       $src,         $token_str);
        $src    = preg_replace(      '/".*"/',         ' STRING! ',   $src);
        // "fix" array delimiters
        $src    = str_replace(      '[',             ' [ ',          $src);
        $src    = str_replace(      ']',             ' ] ',          $src);
        // split on whitespace
        $src    = preg_split (      '/\s+/',          $src);
       
        $msg    = '';
        $stack  = array();
   
        // take each token in turn...
        $level  = 0;
        $items  = 0;
        foreach ($src as $_token) {
            $token      = trim($_token);
            $last_char  = substr($token, strlen($token) - 1, 1);
            $stack[]    = $items;
            switch ($last_char) {
                case '[':
                    // array start
                    $msg .= "array(";
                    ++$level;
                    $stack[] = $items;
                    $items = 0;
                    break;
                case ']':
                    // array end
                    $msg .= ")";
                    $items = array_pop($stack);
                    ++$items;
                    --$level;
                    break;
                case ':':
                    if ($level == 0) {
                        if ($items > 0) {
                            $msg .= ';';
                        }
                        $msg .= "$" . substr($token, 0, strlen($token) - 1) . "=";
                    } else {
                        if ($items > 0) {
                            $msg .= ',';
                        }
                        $msg .= '"' . substr($token, 0, strlen($token) - 1) . '"=>';
                    }
                    // assignment
                    ++$items;
                    break;
                case '!':
                    // pre tokenized type
                    switch ($token) {
                        case 'STRING!':
                            $msg .= array_shift($token_str[1]);
                            break;
                    }
                    break;
                default:
                    $msg .= $token;
                    break;
            }
        }
        $msg .= ';';
        $cnt = preg_match_all('/(\$(\w+)\s*=\s*(.*?;))/', $msg, $list);
        $cnt = count($list[1]);
        if ($cnt > 0) {
            for ($i = 0; $i < $cnt; $i++) {
                $var = $list[2][$i];
                if (!empty($var)) {
                    eval ($list[1][$i]);
                    $smarty->assign($var, $$var);
                }
            }
        }

    }
}
?>


sample.tpl

Code:
{dsrlz}
catelog: [
   Men:   ["Out Wear", "Knitwear", "Sports Wear"]
   Women:   ["Out Wear", "Knitwear", "Sports wear"]
   Kids:   ["Knit wear", "Sports wear"]
]
{/dsrlz}


The sample code only makes the assignments: it does not output any results. The parser is simple and hasn't been tested extensively, but I know it works for cases like this. It does not allow escaped quotes. It can be made simpler but I pulled it out of a larger data-compiler that I'm tinkering with (which is why it generates PHP code internally).

On the topic of data serialization, has anyone toyed with YAML or SYCK yet?

edited: corrected some errors


Last edited by boots on Thu Oct 28, 2004 3:53 pm; edited 5 times in total
Back to top
View user's profile Send private message
boots
Administrator


Joined: 16 Apr 2003
Posts: 5611
Location: Toronto, Canada

PostPosted: Tue Apr 22, 2003 7:30 am    Post subject: Reply with quote

For completeness, I'm posting a function plugin that does the reverse operation: converts an assigned variable (or value) to a text representation compatable with the {dsrlz} plugin above.

add the following to your plugin directory:

function.srlz.php

Code:
<?php

/**
 * Smarty {srlz} function plugin
 * -------------------------------------------------------------
 * Type:     function<br>
 * Name:     srlz<br>
 * Version:  1.0
 * Author:    boots
 *
 * @param value required variable of value to be serialized
 * @param var optional if set, smarty assigns serialed value
 *                     to $var without output
 */
function smarty_function_srlz($params, &$smarty)
   {
   extract($params);
   if (empty($value))
      {
      $smarty->trigger_error("srlz: missing 'value' parameter");
      }

   $retval = _srlz($value);

   if (!empty($var))
      {
      $smarty->assign ($var, $retval);
      }
   else
      {
      return $retval;
      }
   }

function _srlz($data)
   {
   if (is_array($data))
      {
      $retval = '[';
      foreach ($data as $k=>$v)
         {
         $use_key = (!$k || !is_string($k)) ? False : True ;
         if ($use_key)
            {
            $retval .= "$k: ";
            }
         if (is_array($v))
            {
            $retval .= _srlz($v);
            }
         else if (is_string($v))
            {
            $retval .= '"' . $v . '"';
            }
         else
            {
            $retval .= $v;
            }
         if ($use_key)
            {
            $retval .= "\n";
            }
         else
            {
            $retval .= ",";
            }
         }
      $retval = substr($retval, 0, strlen($retval)-1);
      $retval .= ']'."\n";
      }
   else if (is_string($data))
      {
      $retval = '"' . $data . '"'."\n";
      }
   else
      {
      $retval = $data."\n";
      }
   return $retval;
   }   

?>


Which allows you to do the really silly:

Code:
{dsrlz}
level1: [level2: "tee hee"]
{/dsrlz}

serialized representation of $level1:<br/>
{srlz value=$level1}<br/><br/>

{dsrlz}
top: [middle: {srlz value=$level1}]
{/dsrlz}

serialized representation of $top:<br/>
{srlz value=$top var=top_s}
{$top_s|replace:"]":"]<br/>"}


Note: Using {srlz value=$top var=top_s} the plugin smarty assigns the serialized value into $top_s without any output.

I would have prefered to write this as a modifier since it seems to beg for a {$level1|srlz} syntax, but it seems that modifiers don't like to be passed anything but straight text--I seem to need a modifier that passes the reference instead of the value.

What would happen if the existing plugin modifier interface did pass a reference when it encounters non scalars and pass values otherwise?

edited: corrected some errors
Back to top
View user's profile Send private message
bqh19
Smarty n00b


Joined: 21 Apr 2003
Posts: 2

PostPosted: Tue Apr 22, 2003 8:35 pm    Post subject: Reply with quote

Thanks a lot for you all!

Brian
Back to top
View user's profile Send private message
danny36
Smarty Rookie


Joined: 14 Jul 2004
Posts: 27
Location: Italy - Arezzo (Tuscany)

PostPosted: Thu Oct 28, 2004 3:06 pm    Post subject: Reply with quote

I try to test this plugin but I receive this warning and I don't see any result!

Code:
{dsrlz}
level1: [level2: "tee hee"]
{/dsrlz}

serialized representation of $level1:<br/>
{srlz value=$level1}<br/><br/>


result in browser:
Code:
serialized representation of $level1:

Warning: Smarty error: srlz: missing 'value' parameter in C:\php\smarty\libs\Smarty.class.php on line 1089
Back to top
View user's profile Send private message Visit poster's website
boots
Administrator


Joined: 16 Apr 2003
Posts: 5611
Location: Toronto, Canada

PostPosted: Thu Oct 28, 2004 3:56 pm    Post subject: Reply with quote

Sorry danny36--I should have known better than to link to a post I wrote over a year-and-a-half ago which contains code that I don't even use Smile. Actually, I use a different version of this code but I connect it to Smarty using filters and resources instead of plugins.

Anyways, the problem was with dsrlz which I updated (to 1.1). It should work now, but let me know if you have any problems. I also simplified it a little so that it now no longer takes "file" or "var" parameters. Note that the srlz that is presented here is likely not needed and features a pretty crummy implementation anyhow.

I'll probably make the full implementation that I actually use available at some point, but not anytime soon, so hopefully this will meet your needs.
Back to top
View user's profile Send private message
danny36
Smarty Rookie


Joined: 14 Jul 2004
Posts: 27
Location: Italy - Arezzo (Tuscany)

PostPosted: Thu Oct 28, 2004 4:06 pm    Post subject: Reply with quote

yes now work fine! Laughing thanks

one another question, I can access to variable inside the block from the another plugin (my custom plugin) ??? how to do this? Wink
Back to top
View user's profile Send private message Visit poster's website
boots
Administrator


Joined: 16 Apr 2003
Posts: 5611
Location: Toronto, Canada

PostPosted: Thu Oct 28, 2004 4:37 pm    Post subject: Reply with quote

danny36 wrote:
one another question, I can access to variable inside the block from the another plugin (my custom plugin) ??? how to do this? Wink


I'm not exactly sure what you mean--can you give a rough example of what you are trying to do?
Back to top
View user's profile Send private message
danny36
Smarty Rookie


Joined: 14 Jul 2004
Posts: 27
Location: Italy - Arezzo (Tuscany)

PostPosted: Fri Oct 29, 2004 7:06 am    Post subject: Reply with quote

for example, I've a template with this code:
Code:
test4: ["test1", "test2", "test3"]
whole another settings, how can I give the value (test1,test2,test3) in block.dsrlz.php or send this values to another plugin?
Back to top
View user's profile Send private message Visit poster's website
boots
Administrator


Joined: 16 Apr 2003
Posts: 5611
Location: Toronto, Canada

PostPosted: Fri Oct 29, 2004 1:05 pm    Post subject: Reply with quote

Again, I'm finding it difficult to follow you on such few words. I'll give it a try:

Code:
{dsrlz}
test4: ["test1", "test2", "test3"]
{/dsrlz}

{myfoo bar=$test4}


Now myfoo recieves the parameter bar which is = array("test1", "test2", "test3").

Is that what you mean?

To be honest, this version of dsrlz/srlz was not meant to be accessed directly from PHP code, but rather from a template.
Back to top
View user's profile Send private message
linkage8055
Smarty n00b


Joined: 04 Jun 2009
Posts: 1

PostPosted: Thu Jun 04, 2009 8:19 am    Post subject: {srlz} Empty or (String " ) Code Not Parser Change Reply with quote

Code:

function _srlz($data) {
  if(is_array($data)) {
    $retval = '[';
   
    foreach ($data as $k=>$v) {
      $use_key = (!$k || !is_string($k)) ? false : true ;
      if ($use_key) $retval .= "$k: ";

      if (is_array($v)) $retval .= _srlz($v);
        else if (is_string($v)) {
          $v=str_replace('"', '\"', $v); 
          $retval .= '"' . $v . '"';
        } else {
                 if(!is_numeric($v) and empty($v)) {
                   $v=gettype($v);               
                   if(strtoupper($v)=='ARRAY') $v.='()';
                 }
                 $retval .= $v;
               }
      if ($use_key) $retval .= "\n"; else $retval .= ",";
    }
    $retval = substr($retval, 0, strlen($retval)-1);
    $retval .= ']'."\n";
   
  } else if(is_string($data)) $retval = '"' . $data . '"'."\n";  else $retval = $data."\n";
  return $retval;
}
Back to top
View user's profile Send private message Send e-mail
Display posts from previous:   
Post new topic   Reply to topic    Smarty Forum Index -> Smarty Development All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group
Protected by Anti-Spam ACP