2

I am trying to display a paragraph & want to highlight few words.

Let's suppose i have a paragraph, For example - "Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document."

I want to highlight word template if exits.

this paragraph & word is coming from flask.

displaying paragraph using bootstrap like this -

<td><b>Sentence :</b> {{ data['sentence'] }}</td><br>

created a style -

.highlight{
    background-color: yellow;
}

I am not getting how to search that word in this paragraph & apply style to that word only.

Edit - I am getting data from db like this.

[

    {
        "_id":{
            "$oid":"60xxxxxxxx"
        },
        "bookName":"index.txt",
        "author":"",
        "publishDate":"",
        "lineNo":1,
        "paragraph":"Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document."
    },
    {
        "_id":{
            "$oid":"60xxxxxxxx"
        },
        "bookName":"index.txt",
        "author":"",
        "publishDate":"",
        "lineNo":1,
        "paragraph":"Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document."
    }

]

Tried-

<script type="">
    document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", "<mark>{{word}}</mark>");
    // document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", "<mark>{{word}}</mark>");
    // document.addEventListener('DOMContentLoaded', function () {
    //     document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", "<mark>{{word}}</mark>");
    // });
    // document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", '<mark>'+'{{word}}'+'</mark>');
    // document.getElementById('para').innerHTML = document.getElementById('para').innerHTML.replace("{{word}}",'<mark>{{word}}</mark>');
</script>

enter image description here

gives error - "can not read property of innerhtml null"

Could anyone please guide.

Thanks,

Jay

1 Answers1

2

Inside your flask route where you receive the sentence you could replace the word template with <mark>template</mark>

The HTML element represents text which is marked or highlighted for reference or notation purposes, due to the marked passage's relevance or importance in the enclosing context.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark

Example:

from flask import Flask, render_template
from markupsafe import Markup

app = Flask(__name__)


@app.route("/")
def index():
    sentence = "Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax. Then the template is passed data to render the final document."
    data = {"sentence": Markup(sentence.replace("template", "<mark>template</mark>"))}
    return render_template("index.html", data=data)


if __name__ == "__main__":
    app.run()

You can still add the class to the mark tag if you want to change the default background-color.


The same approach can also be done with Javascript:

document.body.innerHTML = document.body.innerHTML.replaceAll(
  "template",
  "<mark>template</mark>"
);

You could put this somewhere inside some script tags in the template.


In case the DOM hasn't loaded yet and the above doesn't work try:

window.addEventListener("load", function () {
  document.body.innerHTML = document.body.innerHTML.replaceAll(
    "{{word}}",
    "<mark>{{word}}</mark>"
  );
});

For more info on this, see this post.

5eb
  • 14,798
  • 5
  • 21
  • 65
  • i am getting error, because data is cursor object. I have edited . could you please have a look & guide. – Jay Prakash Thakur Jul 01 '21 at 19:14
  • Is data a cursor object or is it a list like it seems to be in your edit? Either way once you have this list you can loop over it in your template or select an element in the list. The idea in the example above can be applied for each element in the list. – 5eb Jul 01 '21 at 19:50
  • 1
    I've also added a way to do it with Javascript to the answer. – 5eb Jul 01 '21 at 20:00
  • – Jay Prakash Thakur Jul 01 '21 at 20:26
  • added this in body but no luck. – Jay Prakash Thakur Jul 01 '21 at 20:26
  • 1
    @JayPrakashThakur Needs more quotes: `document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", ""+"{{word}}"+"" );`. Alternatively you could also use template literals for a cleaner syntax: document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", `{{word}}` );. Backticks messes the formatting on SO up unfortunately, but should still show the idea. – 5eb Jul 01 '21 at 20:29
  • on inspecting element, it gives me "Unexpected token" error – Jay Prakash Thakur Jul 01 '21 at 20:55
  • Yeah like I mentioned the formatting on stackoverflow kind of messes the second example in my comment up. But now that I think of it backticks are not necessary either here, double quotes work too since we're using jinja: `document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", "{{word}}" );` – 5eb Jul 01 '21 at 21:03
  • TypeError: null is not an object (evaluating 'document.body.innerHTML') – Jay Prakash Thakur Jul 01 '21 at 21:11
  • DOM might not have loaded. You can try wrapping the code in an event listener that listens for page load. See [this post](https://stackoverflow.com/questions/27833117/typeerror-document-body-is-null). – 5eb Jul 01 '21 at 21:18
  • document.getElementById('para').innerHTML = document.getElementById('para').innerHTML.replace("{{word}}",'{{word}}'); tried this, no luck – Jay Prakash Thakur Jul 01 '21 at 21:24
  • document.addEventListener('DOMContentLoaded', function () { document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}", "{{word}}"); }); tried this one too, no luck – Jay Prakash Thakur Jul 01 '21 at 21:26
  • You're missing a closing bracket in your last comment `"{{word}"` needs to be `"{{word}}"`. – 5eb Jul 01 '21 at 21:29
  • yeah, i tried with both bracket. didn't work. – Jay Prakash Thakur Jul 01 '21 at 21:34
  • window.addEventListener('load', function () { document.body.innerHTML = document.body.innerHTML.replaceAll("{{word}}", "{{word}}"); }); this worked. please add this to ans, will accept. – Jay Prakash Thakur Jul 01 '21 at 21:49
  • 1
    Good to hear you got it working. I've updated my answer. – 5eb Jul 01 '21 at 21:54
  • Thank you so much for all your help. – Jay Prakash Thakur Jul 01 '21 at 22:16
  • but now it shows issue - it loads all the html tags instead of pasing it. could you please guide. – Jay Prakash Thakur Jul 01 '21 at 22:25
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234431/discussion-between-bas-van-der-linden-and-jay-prakash-thakur). – 5eb Jul 02 '21 at 05:25