Search code examples
pythonhtmljinja2

Split keys and values from dict in Jinja2 href tag


I have html Jinja2 template with for loop which contains keys and values from dictionary. But all my keys stuck together in <a> </a> tag like

Part1: <Status> (component1component2component3)

How I can split it with comma delimiter as I expected?

Part1: <Status> (component1, component2, component3)

My code

from http.server import HTTPServer, SimpleHTTPRequestHandler
from jinja2 import Environment, FileSystemLoader, select_autoescape
import os

def part1_status ():
    Part1StatusFile = "Part1_Status"
    componentsFile = "Part1_Components" 
    linksFile = "Part1_Links"
    with open(Part1StatusFile) as file:
        if 'OK' in file.read():
            Part1Status = "OK"
            part1_result = {}
        else:
            Part1Status = "KO"
            if os.path.isfile(componentsFile) and os.path.isfile(linksFile) == True:
                with open(componentsFile) as f:
                    components = f.read().split(", ")
                with open(linksFile) as f:
                    links = f.read().split(", ")  

                part1_result = {components[i]: links[i] for i in range(len(components))}
            else: 
                part1_result = {}    

        return part1_result, Part1Status

part1_result, Part1Status = part1_status ()

env = Environment(
    loader=FileSystemLoader('.'),
    autoescape=select_autoescape(['html', 'xml'])
)

template = env.get_template('email.html')

rendered_page = template.render(
    Part1Status = Part1Status,
    part1_result = part1_result
)

with open('index.html', 'w', encoding="utf8") as file:
    file.write(rendered_page)

server = HTTPServer(('0.0.0.0', 8000), SimpleHTTPRequestHandler)
server.serve_forever()
<div id="Backend">
 <h4>Backend:</h4>
  <ul>
   <li>Part1: {{Par1Status}} {% for key, value in result.items(): %}<a href={{value}}>{{key}}</a>{% endfor %}</li>
   </ul> 
</div>

I tried to adding {{key.split(", ")}} but in this case I got keys in square brackets


Solution

  • Jinja provides some special loop variables that we can use to check whether we are at the last item or not. We need to put a {% if not loop.last %}, {% endif %} after the item to insert the separator:

    Part1: {{Par1Status}} ({% for key, value in result.items(): %}<a href={{value}}>{{key}}</a>{% if not loop.last %}, {% endif %}{% endfor %})