I am using v-html to strip html tags but still show the processed html. Problem is, I only want 200 characters to show. I can build truncating scripts but v-html doesn't seem to take filters. How can I achieve this?
For example:
// This
<div class="excerpt" v-html="body_html"></div>
// Into this
<div class="excerpt" v-html="body_html | truncate(200)"></div>
I tried building a striptag filter and truncate + strip the tags of a regular <p>
but it didn't process the html. In other words, I got raw HTML back without any bold, italics, etc
For example, like this:(not my preferred method, unless you can find a way for me to improve it so I can still get rendered HTML.
<div>{{strippedContent | truncate(200)}}</div>
Vue.filter("truncate", function(value, length) {
if (!value) return "";
value = value.toString();
if (value.length > length) {
return value.substring(0, length) + "...";
} else {
return value;
}
});
export default {
data() {
return {
body_html: this.post.body_html
};
},
puted: {
strippedContent() {
let regex = /(<([^>]+)>)/gi;
return this.body_html.replace(regex, "");
}
}
};
I am using v-html to strip html tags but still show the processed html. Problem is, I only want 200 characters to show. I can build truncating scripts but v-html doesn't seem to take filters. How can I achieve this?
For example:
// This
<div class="excerpt" v-html="body_html"></div>
// Into this
<div class="excerpt" v-html="body_html | truncate(200)"></div>
I tried building a striptag filter and truncate + strip the tags of a regular <p>
but it didn't process the html. In other words, I got raw HTML back without any bold, italics, etc
For example, like this:(not my preferred method, unless you can find a way for me to improve it so I can still get rendered HTML.
<div>{{strippedContent | truncate(200)}}</div>
Vue.filter("truncate", function(value, length) {
if (!value) return "";
value = value.toString();
if (value.length > length) {
return value.substring(0, length) + "...";
} else {
return value;
}
});
export default {
data() {
return {
body_html: this.post.body_html
};
},
puted: {
strippedContent() {
let regex = /(<([^>]+)>)/gi;
return this.body_html.replace(regex, "");
}
}
};
Share
Improve this question
asked Jan 19, 2020 at 2:53
LOTUSMSLOTUSMS
10.3k18 gold badges78 silver badges153 bronze badges
1 Answer
Reset to default 9Can you try another (local) way from the docs https://v2.vuejs/v2/guide/filters.html ?
Global (your way) registering of the filter should be made before creating the Vue instance. Can you check it?
Upd. Also there are bugs on working together v-html and filters:
- "v-html does not work with filters" https://github./vuejs/vue/issues/4352
- "Vue filter dont work on v-html" https://github./vuejs/vue/issues/6056
SOLUTION
In the template, replace the v-html line with
<div :inner-html.prop="body_html | truncate(250)"></div>
The striphtml filter is not needed any longer