简体   繁体   中英

Python Jinja2 Render HTML template in certain style from strings

I am new to using Jinja2 and am trying to render an html file from several strings and lists.

Lets say I have a File path, a term, and a sentence.

Using these I want to create an html file which has the file path as well as the two sentences where the the word is bolded if it matches the term.

Ie

file_path is "/usr/bin/local/cheese.txt"

term is "cheese"

sentence is "i am cheese cheese i am"

I want to create and html file that looks like this

<html>
    <body>
    <h2>Search results for <b>cheese</b> in the file</h2>

        <p><a href="/usr/bin/local/cheese.txt">/usr/bin/local/cheese.txt</a><br>
         I am <b>cheese</b> <b>cheese</b> I am<br><br>

</body>
</html>

I have been trying to use Jinja2 but am having trouble creating an HTML file by specifying the formatting.

Here is what I have so far:

import jinja2
from jinja2 import Environment, FileSystemLoader

def render_template(template_filename, context):
    return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)




file_path = "/usr/bin/local/cheese.txt"



term = "cheese"

sentence = "i am cheese cheese i am"

context = {
         'h2': "Search results for <b>" + terms + "</b>",
        'urls': file_path, # for making the file path tag - not sure if right
        'bold': term, # Do not think this is correct
        'paragraph': sentence ## Do not think this is correct at all.

    }

output = template.render_template("temp.html", context)

I do not think this is correct, but if someone who knows Jinja2 please tell me how to format this correctly I would be most grateful.

Please let me know if you need any more information.

Thank you for your time.

That's an example of your code in jinja2:

Python:

from jinja2 import Template


def render_template(template_filename, context):
    with open(template_filename) as file_:
        template = Template(file_.read())
    return template.render(context)


file_path = "/usr/bin/local/cheese.txt"
term = "cheese"
sentence = "i am cheese cheese i am"
if term in sentence:
    sentence = sentence.replace(term, '<b>%s</b>' % term)
context = {
        'h2': "Search results for <b>" + term + "</b>",
        'urls': file_path,
        'bold': term,
        'paragraph': sentence

    }

output = render_template(your_template, context)
print(output)

Your template:

<html>
    <body>
    <h2>{{ h2|safe }}</h2>

        <p><a href="{{ urls }}}}">{{ urls }}}}</a><br>
         {{ paragraph|safe }}<br><br>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM