silverstripe / silverstripe-framework

Silverstripe Framework, the MVC framework that powers Silverstripe CMS
https://www.silverstripe.org
BSD 3-Clause "New" or "Revised" License
720 stars 820 forks source link

Ability to loop through containers containing primitives in Silverstripe templates #11196

Closed chrispenny closed 1 month ago

chrispenny commented 2 months ago

Description

It would be great if we were able to pass simple numeric/non-associative arrays to Silverstripe templates for them to be output. MVP for me would also be when those arrays only contain simple data types (string, int, float, etc).

I think this is probably felt most (for me) when working with external data sources. Trying to output some simple indexed content all of a sudden requires a bunch of processing before you can return it to your template.

As an aside, in Silverstripe 3, this would work:

class MyController extends PageController
{
    public function ArrayListTest()
    {
        return new ArrayList(['item1', 'item2', 'item3']);
    }
}
<% loop $ArrayListTest %>
    $Me
<% end_loop %>

But now in Silverstripe 4 and 5, this results in an error:

[Emergency] Uncaught Error: Call to a member function XML_val() on string

Noting though, that I'd probably prefer to avoid needing to convert my array to an ArrayList, as that still requires processing.

Additional context or points of discussion

No response

Acceptance criteria

New issues created

Kitchen-sink CI run

PRs

GuySartorelli commented 2 months ago

This is a good idea. The template engine should be able to check if the value it's operating on is an object or not, and if it's not an object give it the appropriate DBField casting (bool to DBBoolean, etc)

maxime-rainville commented 2 months ago

@GuySartorelli added this to the 5.3 milestone.

This looks like the potential for a quick win.

I added a very generic AC just to avoid pre-judging of the best way of doing this

I'm thinking of the top of my head:

GuySartorelli commented 2 months ago

The first two options there are just an implementation detail, really. Whether SSViewer (or the template parser, etc etc) wraps the primitive or just deals with it directly doesn't really matter - what matters is that developers don't have to do that part themselves.

That third option would have to be in a major release, and goes in the wrong direction imo. I'd prefer to see ArrayList not wrap any values in ArrayData at all, even in the cases it currently does.

GuySartorelli commented 1 month ago

PRs merged