3
votes

I am trying to use Vue.js in Django templates. One such template is the following:

{% load static %}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <div id="myApp">
        <span>Hello [[ message ]]</span>
        <div id="map"></map>
    </div>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://v1.vuejs.org/js/vue.js"></script>
    <script src="{% static 'js/script.js' %}"></script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"></script>
</body>

</html>

I changed Vue's interpolation delimiters to [[ ]] to avoid conflict with Django. My script.js looks as follows:

$(function() {
    var app = new Vue({
        el: '#myApp',
        delimiters: ['[[', ']]'],
        data: {
            message: 'Hello, world!'
        }
    });
});

Unfortunately, the HTML rendered contains [[ message ]]. Has anyone else faced a similar issue?

2
What version of vue are you using? - nik_m
Quite surprisingly, v-text="message" directive works - Yash Mittal

2 Answers

10
votes

As the per docs of Vue v1.0 say:

// ES6 template string style
Vue.config.delimiters = ['${', '}']

So, in your example change to:

$(function() {
    Vue.config.delimiters = ['[[', ']]'];
    var app = new Vue({
        el: '#myApp',
        data: {
            message: 'Hello, world!'
        }
    });
});

It is strongly recomended, though, to use the new version of Vue (version 2) in order to be up-to-date!

4
votes

Django has builtin functionality to skip interpreting template using verbatim

<div id="myApp">
    {% verbatim %}
       {{ value_from_vue }}
    {% endverbatim %}
    {{ value_from_django }}
</div>

<script>
    var myApp = new Vue({
        el: '#myApp',
        data: {
            value_from_vue: "hello from vue"
        }
    })
</script>

Anything goes inside verbatim won't be interpreted by the django template engine. This functionality also useful for other (if any) Javascript libraries when they don't provide delimiter option.

However, if configuring delimiter is preferred:

for latest Vue (version 2+), put the config inside the vue instance just like in the question.

$(function() {
    var app = new Vue({
        el: '#myApp',
        delimiters: ['[[', ']]'],
        data: {
            message: 'Hello, world!'
        }
    });
});

for Version 1 of Vue, use just like the answer by nik_m

Vue.config.delimiters = ['[[', ']]'];