ReynierPM ReynierPM - 4 months ago 11
PHP Question

Assign value to var in Smarty from specific values

Can I assign this:

{{$phone_numbers.0.phone_number}}
{{if $phone_numbers.0.extension}} EXT. {{$phone_numbers.0.extension}}{{/if}}


to a var in Smarty3? How? I have seen
assign
but I don't know how to concatenate values using it, any help?

EDIT: is this the right way?

What do you think about this:

{{$phone_number=$phone.phone_number}}
{{if $phone.extension}} {{$phone_number|cat:"EXT. $phone.extension"}}{{/if}}

Answer

You cannot use conditionals in {assign} but you can use {capture}:

{{capture name=foo assign=bar}}
  {{$phone_numbers.0.phone_number}} 
  {{if $phone_numbers.0.extension}} EXT. {{$phone_numbers.0.extension}}{{/if}}
{{/capture}}

This renders the content of the {capture} block but doesn't output it. Instead it stores is for later use.

You can find it in {$smarty.capture.foo} or in the variable {$bar}.

The assign attribute is optional; you don't use it and the variable {$bar} (or whatever name you use) is not modified. However, the captured content is always stored in the variable {$smarty.capture.foo} (or whatever name you use for it).

Comments