Search code examples
htmlsmarty

Iterate an object using SMARTY?


I've been trying to iterate {"username":"testuser","password":"XXXXXX"} in smarty(3.1.29). I need to print those keys and values inside a panel. I cannot iterate over this.

Even I tried with PHP array a:2:{s:8:"username";s:6:"ubuntu";s:8:"password";s:8:"password";} I cannot iterate this.

$json = {
           "username":"testuser",
           "password":"XXXXXX"
         }
{foreach from=$json item=key key=val} 
     Key  : {key}
     Value: {value} 
{/foreach}

Is there any way possible to iterate over this?

I want output like below:

Key : testuser
Value : XXXXX

Solution

  • You could try converting the JSON object to a PHP array first:

    $userJson = {"username":"testuser","password":"XXXXXX"}
    
    $userArray = json_decode($userJson)
    
    $smarty->assign("userArray", $userArray);
    

    Then in Smarty it would be:

    {foreach from=$userArray key=key item=value}
       <li>{$key}: {$value}</li>
    {/foreach}