lapinkoira
lapinkoira

Reputation: 8978

How to escape single quote for a prop?

I have a Django context variable which is a jsonified list of strings but some of those strings might have a single quote '

import json
list_of_strings = ["test", "hello", "I have a'single quote"]
return render(request, 'template.html', {
    'strings': json.dumps(list_of_strings)
})

Then I insert it into a vue component through one of his props which, as you can see, must be wrapped between single quotes.

:strings='{{ strings|safe }}'

But it crashes, just insert the list until the first single quote and then writes everything else as text in the browser.

How can I escape it?

Upvotes: 4

Views: 6156

Answers (2)

Neil
Neil

Reputation: 9453

Roy J's answer is correct, but in case it is not obvious to others you need to assign the json to a javascript variable and then pass it to v-bind.

eg

<script>
var list_of_strings = {{ list_of_strings|safe }};
</script>

<my-component v-bind:strings="list_of_strings"></my-component>

Upvotes: 0

Roy J
Roy J

Reputation: 43881

This works fine. If the array is being used as a variable, simply v-bind the variable name. if the array is being injected into the component instantiation, you would need to replace single quotes with backslash-single quotes.

new Vue({
  el: '#app',
  data: {
    list_of_strings: ["test", "hello", "I have a'single quote"]
  },
  components: {
    showString: {
      props: ['strings']
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <show-string :strings="list_of_strings" inline-template>
    <div>
      <div v-for="s in strings">{{s}}</div>
      <div v-for="s in ['some', 'array', 'single\'quote']">{{s}}</div>
    </div>
  </show-string>
</div>

Upvotes: 4

Related Questions