XF 2.2 Calling a variable ($mediaItems) from inside a script

Orit

Active member
Hi
I'm trying to use the $mediaItems variable inside a script.
Is that possible?

specifically, I have some javascript code for a slider that I'm trying to use on my website.

Thanks!
 
I currently have this code that works:
HTML:
<xf:foreach loop="$mediaItems" key="$key" value="$mediaItem">
    <script>
        mediaItem = {
            id: '{$mediaItem.media_id}',
            title: '{$mediaItem.title}',
            desc: '{$mediaItem.description}',
            type: '{$mediaItem.media_type}',
            url: "{{ link('media/full', $mediaItem, {'d': $mediaItem.last_edit_date ?: null}) }}"
        }
        //arr.push('{$mediaItem.media_id}');
        mediaItems.push(mediaItem);
    </script>
</xf:foreach>

I basically created my own array of objects and used them in my Javascript code (mediaItems is declared as an empty array in a separate script tag outside of the foreach loop).
trying to use the variable directly resulted in an error: Object of class XF\Mvc\Entity\ArrayCollection could not be converted to string

Is there a better way to use xenforo variables in a script tag?
 
Ok, so this method:
JavaScript:
mediaItem = {
            id: '{$mediaItem.media_id}',
            title: '{$mediaItem.title}',
            desc: '{$mediaItem.description}',
            type: '{$mediaItem.media_type}',
            url: "{{ link('media/full', $mediaItem, {'d': $mediaItem.last_edit_date ?: null}) }}"
        }

works well, given there are no line breaks in the variables.
The description: desc: '{$mediaItem.description}' often has line breaks and that breaks my code.

How can I call the variable and make sure to remove the line breaks?

I forgot to send my question, and found a solution in the meantime :ROFLMAO::ROFLMAO:

So in case anyone else comes across a similar issue,
I solved it by setting a variable (in the HTML, outside the script tag):
<xf:set var="$description" value="{{$mediaItem.description | escape('js')}}" />
this ensures the string does not have line breaks and the code works perfectly :)
Enjoy!
 
Back
Top Bottom