Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output html from filter inside mustache

I have a input (top right) where users can search things, when it's directive length get 3 characters it will display a list of products and highlight the matches...

Look at my code:

html

<div id="app">
  <div id="header">
    <div class="right"><input type="text" v-model="message" v-on:keyup="searchStart()" v-on:blur="searchLeave()"/>
      <ul v-if="this.searchInput" class="product-list">
      <li v-for="product in products">
        {{ product.id }} - {{ product.name | highlight }} - {{ product.qtd }}</li></ul>
    </div>
  </div>
  <div id="main">
    <div id="menu">fdfds</div>
    <div id="container">{{ message }}</div>
  </div>
</div>

js

var search = new Vue({
  el: "#app",
  data: {
    message: "",
    searchInput: false,
    products: [
      {
        id: 1,
        name: "produto 01",
        qtd: 20
      },
      {
        id: 2,
        name: "produto 02",
        qtd: 40
      },
      {
        id: 3,
        name: "produto 03",
        qtd: 30
      },
    ]
  },
  methods: {
    searchStart: function(){
      if(this.message.length >= 3)
        this.searchInput = true;
      console.log(this.searchInput);
    },
    searchLeave: function(){
      this.searchInput = false;
      this.message = "";
      console.log(this.searchInput);
    }
  },
  filters: {
    highlight: function(value){
      return value.replace(search.message, '<span class=\'highlight\'>' + search.message + '</span>');
    }
  }
});

Here you can see a live pen: http://codepen.io/caiokawasaki/pen/dXaPyj

try to type prod inside the pen...

Is my filter correct? The way I created the filter is correct?

The main question is: How to output the HTML from my filter?

Edit/Solution

The problem in the case was codepen, there is some kind of conflict with vue, so I was not able to escape the html using {{{}}}, put the code in another editor (jsfidle) and it worked.

I'm accepting the answer given to the reward because it's right.

like image 986
Caio Kawasaki Avatar asked Aug 12 '16 19:08

Caio Kawasaki


1 Answers

You'll need 3 steps here for achieve what you want:

  • Use triple braces {{{ }}} to display unescaped html
  • Filter your users by your v-model variable, in order to just show the matches
  • Replace the substring matching by the <span> tag

Check out the computed property filteredUsers and the filter in this working jsfiddle

like image 67
Alex JM Avatar answered Oct 02 '22 06:10

Alex JM