How to render by Vue instead of Jinja

2019-01-11 01:37发布

<template id="task-template">
    <h1>My Tasks</h1>
    <tasks-app></tasks-app>
    <ul class="list-group">
        <li class="list-group-item" v-for="task in list">
            {{task.body|e}}
        </li>
    </ul>
</template>

This above is my html. I want to render the code by Vue instead.

<script>
    Vue.component('tasks-app', {
        template: '#tasks-template',
        data: function() {
            return {
                list: []
            }
        }
        created: function() {
            $.getJson('/api/tasks', function(data) {
                this.list = data;
            })
        }
    })
    new Vue({
        el: 'body',
    });
</script>

The above is my Vue code, and Jinja raise an exception that 'task' is undefined, what I hope for is that the html code rendered by Vue instead of Jinja, I know it could be done in Laravel with this:

"@{{task.body}}"

Since I am new to Jinja, could anyone help me out?

5条回答
走好不送
2楼-- · 2019-01-11 02:13

Configure Vue v2 class instance with the 'delimiters' option:

<div id='myapp'> !{ message } </div>
<script>
let myapp = new Vue({ delimiters: ['!{', '}'], ...});
</script>

Source: https://vuejs.org/v2/api/#delimiters

查看更多
不美不萌又怎样
3楼-- · 2019-01-11 02:14

If you're using Flask, you can redefine the delimiters used by Jinja:

class CustomFlask(Flask):
    jinja_options = Flask.jinja_options.copy()
    jinja_options.update(dict(
        variable_start_string='%%',  # Default is '{{', I'm changing this because Vue.js uses '{{' / '}}'
        variable_end_string='%%',
    ))


app = CustomFlask(__name__)  # This replaces your existing "app = Flask(__name__)"
查看更多
聊天终结者
4楼-- · 2019-01-11 02:20

You need to define parts of your template as raw so that Jinja escapes that portion instead of trying to fill it up with its own context.

Here is how you need to do it:

<template id="task-template">
  <h1>My Tasks</h1>
  <tasks-app></tasks-app>
  <ul class="list-group">
    <li class="list-group-item" v-for="task in list">
        {% raw %}{{task.body|e}}{% endraw %}
    </li>
  </ul>
</template>

Ref: http://jinja.pocoo.org/docs/dev/templates/#escaping

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-11 02:33

The other option is to redefine the delimiters used by Vue.js. This is handy if you have a lot of existing template code and you wish to start adding Vue.js functionality to a Flask or Django project.

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

Then in your HTML you can mix your Jinja and Vue.js template tags:

    <div id="app">
      {{normaltemplatetag}}
      [[ message ]] 
    </div>

Not sure when the "delimiters" property was added, but it is in version 2.0.

查看更多
We Are One
6楼-- · 2019-01-11 02:37

Use {{ '{{ vue }}' }}

I had the same problem, and also got it solved.

查看更多
登录 后发表回答