Search code examples
pythonjsonamp-html

Output HTML using a template and JSON for data


What's a good way for me to output (AMP compliant) HTML using a template and JSON for the data? I have a nice little python script:

import requests
import json
from bs4 import BeautifulSoup

url = requests.get('https://www.perfectimprints.com/custom-promos/20492/Beach-Balls.html')
source = BeautifulSoup(url.text, 'html.parser')

products = source.find_all('div', class_="product_wrapper")
infos = source.find_all('div', class_="categories_wrapper")

def get_category_information(category):
  category_name = category.find('h1', class_="category_head_name").text
  return {
    "category_name": category_name.strip()
  }

category_information = [get_category_information(info) for info in infos]

with open("category_info.json", "w") as write_file:
  json.dump(category_information, write_file)

def get_product_details(product):
  product_name = product.find('div', class_="product_name").a.text
  sku = product.find('div', class_="product_sku").text
  product_link = product.find('div', class_="product_image_wrapper").find("a")["href"]
  src = product.find('div', class_="product_image_wrapper").find('a').find("img")["src"]
  return {
      "title": product_name,
      "link": product_link.strip(),
      "sku": sku.strip(),
      "src": src.strip()
  }

all_products = [get_product_details(product) for product in products]

with open("products.json", "w") as write_file:
  json.dump({'items': all_products}, write_file)

print("Success")

Which generates the JSON files I need. However, I now need to use those JSON files and input it into my template (gist) everywhere it says {{ JSON DATA HERE }}.

I'm not even sure where to start. I'm most comfortable with JavaScript so I'd like to use that if possible. I figure something involving Node.js.


Solution

  • Here's how you can render HTML with a template engine by itself and use it to return pure HTML:

    from jinja2 import Template
    
    me = Template('<h1>Hello {{x}}<h1>')
    html = me.render({'x': 'world'})
    return html
    

    html is your rendered HTML string. Alternatively, you can render from a file:

    from jinja2 import Template
    with open('your_template.html') as file_:
        template = Template(file_.read())
    html = template.render(your_dict)
    return html
    

    Since you're going to generate HTML one way or another, using a template engine will save you much time. You can also do {% for item in list %} and such thing will greatly simplify your task.