This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

seanjkanderson58060
seanjkanderson58060

I'm trying to pass the twig variable {{ gallery }} to a javascript function in order to iterate over the twig variable.

When I pass in my twig variable in the scripts section:

<script> 
        var gal = '{{ galleries|json_encode|raw }}';
        loadPortfolioCovers(gal, 'aggregator');
</script>

the issue is that gal loses some child properties. In particular the preserved properties are:

[{"id":1,"name":"TEST_GALLERY","description":"","created_at":"2020-11-17 15:30:41","updated_at":"2020-11-17 15:30:41","slug":"test_gallery","url":"http:\/\/localhost:8888\/laravel_photo\/gallery\/test_gallery"},
{"id":2...},...
]

However, if i were to do the iteration with purely twig then I can still access gallery.images[0].path (the property of interest),

{% for my_gallery in galleries %}
    <p> {{my_gallery.url}}</p>
    <div class="grid-item">
        <div id="send-session" >
            <div class="smoky-container">
                <a href="{{ 'gallery'|page }}/{{my_gallery.name}}">
                <img src="{{ my_gallery.images[0].path }}" alt="" id="send-session" class="button smoky-img"> 
                <p class="smoky-txt"> {{my_gallery.name}} </p> </a>  
            </div>
        </div>
    </div>
    {% endfor %}
</body>

I think this is likely more a json encode issue in JS with nested dictionaries. Alternatively, is there a way to unpack the gallery object in twig and store each gallery.images[0].path in a separate array for JS to iterate over?

Thanks!

Last updated

mjauvin
mjauvin

try passing the JSON_FORCE_OBJECT option to json_encode like this:

data|json_encode(constant('JSON_FORCE_OBJECT'))

Last updated

seanjkanderson58060
seanjkanderson58060

Hmm I tried, "{{ galleries|json_encode(constant('JSON_FORCE_OBJECT')) }}" and "{{ galleries|json_encode(constant('JSON_FORCE_OBJECT'))|raw }}" without success. Is there different datatype (i.e. not JSON) that would be better for encoding a twig variable?

Thanks!

mjauvin
mjauvin

I frankly don't know, but I doubt it.

what about creating a custom twig filter to properly encode this?

ref. https://octobercms.com/docs/plugin/registration#extending-twig

seanjkanderson58060
seanjkanderson58060

My logic ended up being sufficiently simple to write in Twig. Thanks for the help @mjauvin

1-5 of 5

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.