Question

Can someone please tell me how to reference values from an array returned by a smarty modifier

I have a modifier that returns an array

$user = array("name"  => $name, "id" => $id, "email" => $email);
return $user;

When I try to access the returned values in the template using the code below it just says Array

{$member|user_display:"name"}

I have tried lots of different ways and if I use {$member|user_display:"name"|@print_r} it shows the array structure and values so the information is there just need to get at it

Was it helpful?

Solution

Everything depends what functionality you need.

If you simple want to display value for key your code should look like:

Smarty modifier:

function smarty_modifier_user_display($member, $field="name")
{                                                
  // sql searching user  
  $user = array("name"  => 'XXX', "id" => $member.'222', "email" => 'my@example.com');
  return $user[$field];
}

Smarty template file:

{assign var=member value="3"}
{$member|user_display}
{$member|user_display:"name"}
{$member|user_display:"id"}
{$member|user_display:"email"}

But when you have modifier as you showed:

function smarty_modifier_user_display($member)
{                                                
  // sql searching user  
  $user = array("name"  => 'XXX', "id" => $member.'222', "email" => 'my@example.com');
  return $user;
}

Smarty template file should look like this:

{assign var=member value="3"}

{assign var=my_user value = $member|user_display}

{$my_user.name}
{$my_user.id}
{$my_user.email}

You should of course be careful when using modifier - I don't know from what source you get data for your user. But if you do it from database, you shouldn't query database each time because when you launch modifier a couple of times, your database will be unnecessary queried multiple times instead of one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top