Vue.js within Twig

by Sarah Kroll

Vue.js is a great Javascript framework. For one of our clients we created a website based on Craft CMS, where we needed some more interactivity.

Here I decided to use Vue.js.

Pass data to Vue.js from Twig

The first thing we have to do is to create an empty variable where our data will be store which is passed to Vue.js as a property.

{% set data = {} %}

Next we have to loop through our data within twig and then merge the data to our data variable

{% for item in items %}
    {% set data = data|merge([{
        title: item.title,
    }]) %}
{% endfor %}

The next step is to pass this data object to our Vue.js component.

<vue-component :data="{{ data|json_encode }}"></vue-component>

That's it!

Now we are able to use the data props within our Vue component.

Want your own shop?