5

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
            };
        },
        computed: {
            strippedContent() {
                let regex = /(<([^>]+)>)/gi;
                return this.body_html.replace(regex, "");
            }
        }
    };

1 Answer 1

9

Can you try another (local) way from the docs https://v2.vuejs.org/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:

  1. "v-html does not work with filters" https://github.com/vuejs/vue/issues/4352
  2. "Vue filter dont work on v-html" https://github.com/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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I was able to find the solution on the second link you provided. I didn't see that one in my research. This is a reusable vue component, so it's not really needed globally since it will carry every time I use it. But good idea on non-reusable components though. I edited your answer to reflect the solution and so I can mark it as an answer
@LOTUSMS, thank you for editing my answer and marked it as accepted. Now I am able to add comments to questions instead of creating only answers which could be far away from solutions because of my unclear understanding some parts of questions. I hope you will understand what I wanted to say:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.