XF 2.0 How foreach works?

AlessioDP

Member
How can i use a xf:foreach to print an array "list style"?

I'm trying to do that:
Code:
<xf:set var="$listExample"><xf:callback class="Into\\My\\Class" method="getExampleList" params="[{$user.user_id}]"></xf:callback></xf:set>
<xf:foreach loop="$listExample" value="$example">
    Test={$example}
</xf:foreach>

Return of my callback:
Code:
return array("a" => "hey", "b" => "test");

Why foreach doesn't iterate?
 
Your issue here isn't with <xf:foreach> -- it's actually two things that relate to how you're calling <xf:set> and the expectation of <xf:callback>.
  1. xf:callback expects you to return a string (of HTML). Anything other than that will potentially cause undefined behavior.
  2. That syntax for xf:set is designed for setting HTML strings. Anything passed into it will we wrapped in an XF\PreEscaped object and cast to a string. The <xf:set var="$var" value="{{ expression() }}" /> syntax is for more arbitrary variables. (You wouldn't be able to put a callback tag into that, though the HTML string limits mean it wouldn't work anyway.)
If you have to use the callback approach here, you need to wrap everything up in it so that you get the final HTML back.
 
Your issue here isn't with <xf:foreach> -- it's actually two things that relate to how you're calling <xf:set> and the expectation of <xf:callback>.
  1. xf:callback expects you to return a string (of HTML). Anything other than that will potentially cause undefined behavior.
  2. That syntax for xf:set is designed for setting HTML strings. Anything passed into it will we wrapped in an XF\PreEscaped object and cast to a string. The <xf:set var="$var" value="{{ expression() }}" /> syntax is for more arbitrary variables. (You wouldn't be able to put a callback tag into that, though the HTML string limits mean it wouldn't work anyway.)
If you have to use the callback approach here, you need to wrap everything up in it so that you get the final HTML back.

So the only way to make a list with database data it's using a php callback but it must returns an html string, right?
 
In the template, yes. If you require a different approach, we'd recommend using a class extension/event to add the data to the reply view object which would make it available to the template like the existing parameters.
 
The class extension approach would look like:
Code:
<xf:foreach loop="$user.getExampleList()" value="$example">
    Test={$example}
</xf:foreach>
 
Something wrong with that now?

<xf:foreach loop="$result" key="$key" value="$val" >
{$key} :: {$val}
</xf:foreach>
 
Back
Top Bottom