Vue.js Tips on Django

Conflict of Interpolation Marker {{ }}

Both Vue.js and Django’s template use the “moustache” notation for interpolation markers:

<div>Counter: {{ counter }}</div>

The typical sequence of evaluation is:

  • Django templates (Template rendering)
  • Vue.js (Javascript)

Therefore, the snippet above will render whatever’s in Django’s context dict under the key “counter.” By the time Vue.js sees it, it will either be the value of the Django’s template context’s counter or just a blank.

One way to avoid this conflict is to tell Vue.js to use a different notation. The following tells it to use [[ and ]] instead:

<script type="module">
  const { createApp } = Vue
  const app = createApp({
    ...
  })

  // Tell Vue.js to use [[ and ]] markers
  app.config.compilerOptions.delimiters = ["[[", "]]"]
  ...
</script>

With that, Vue.js now can resolve this correctly. It also means both Django context lookup and Vue.js evaluation will work fine side by side.

<div>Counter from Django context: {{ counter }}</div>
<div>Counter from Vue.js: [[ counter ]]</div>