Simple reuse of partial HTML page templates in the Jinja template language for Python web frameworks.

Overview

Jinja Partials

Simple reuse of partial HTML page templates in the Jinja template language for Python web frameworks. (There is also a Pyramid/Chameleon version here.)

Overview

When building real-world web apps with Flask + Jinja2, it's easy to end up with repeated HTML fragments. Just like organizing code for reuse, it would be ideal to reuse smaller sections of HTML template code. That's what this library is all about.

Example

This project comes with a sample flask application (see the example folder). This app displays videos that can be played on YouTube. The image, subtitle of author and view count are reused throughout the app. Here's a visual:

Check out the demo / example application to see it in action.

Installation

It's just pip install jinja-partials and you're all set with this pure Python package.

Usage

Using the library is incredible easy. The first step is to register the partial method with Jinja and Flask. Do this once at app startup:

import flask
import jinja_partials

app = flask.Flask(__name__)

jinja_partials.register_extensions(app)
# ...

Next, you define your main HTML (Jinja2) templates as usual. Then define your partial templates. I recommend locating and naming them accordingly:

├── templates
│   ├── home
│   │   ├── index.html
│   │   └── listing.html
│   └── shared
│       ├── _layout.html
│       └── partials
│           ├── video_image.html
│           └── video_square.html

Notice the partials subfolder in the templates/shared folder.

The templates are just HTML fragments. Here is a stand-alone one for the YouTube thumbnail from the example app:

">
<img src="https://img.youtube.com/vi/{{ video.id }}/maxresdefault.jpg"
     class="img img-responsive {{ ' '.join(classes) }}"
     alt="{{ video.title }}"
     title="{{ video.title }}">

Notice that an object called video and list of classes are passed in as the model.

Templates can also be nested. Here is the whole single video fragment with the image as well as other info linking out to YouTube:

{{ render_partial('shared/partials/video_image.html', video=video) }} {{ video.author }}
{{ "{:,}".format(video.views) }} views
">
<div>
    <a href="https://www.youtube.com/watch?v={{ video.id }}" target="_blank">
        {{ render_partial('shared/partials/video_image.html', video=video) }}
    a>
    <a href="https://www.youtube.com/watch?v={{ video.id }}" target="_blank"
       class="author">{{ video.author }}a>
    <div class="views">{{ "{:,}".format(video.views) }} viewsdiv>
div>

Now you see the render_partial() method. It takes the subpath into the templates folder and any model data passed in as keyword arguments.

We can finally generate the list of video blocks as follows:

{{ render_partial('shared/partials/video_square.html', video=v) }}
{% endfor %} ">
{% for v in videos %}

    <div class="col-md-3 video">
        {{ render_partial('shared/partials/video_square.html', video=v) }}
    div>

{% endfor %}

This time, we reframe each item in the list from the outer template (called v) as the video model in the inner HTML section.

You might also like...
git-partial-submodule is a command-line script for setting up and working with submodules while enabling them to use git's partial clone and sparse checkout features.

Partial Submodules for Git git-partial-submodule is a command-line script for setting up and working with submodules while enabling them to use git's

This repository lets you train neural networks models for performing end-to-end full-page handwriting recognition using the Apache MXNet deep learning frameworks on the IAM Dataset.
This repository lets you train neural networks models for performing end-to-end full-page handwriting recognition using the Apache MXNet deep learning frameworks on the IAM Dataset.

Handwritten Text Recognition (OCR) with MXNet Gluon These notebooks have been created by Jonathan Chung, as part of his internship as Applied Scientis

HTML minifier for Python frameworks (not only Django, despite the name).

django-htmlmin django-html is an HTML minifier for Python, with full support for HTML 5. It supports Django, Flask and many other Python web framework

Blender Game Engine Game Type Templates Logic Bricks (and Python script) based Game Templates for Blender

Blender-Game-Engine-Templates Blender Game Engine Game Type Templates Logic Bric

A Python command-line utility for validating that the outputs of a given Declarative Form Azure Portal UI JSON template map to the input parameters of a given ARM Deployment Template JSON template

A Python command-line utility for validating that the outputs of a given Declarative Form Azure Portal UI JSON template map to the input parameters of a given ARM Deployment Template JSON template

A tool that can encrypt python2 or python3 code with the given password and can reuse with that password
A tool that can encrypt python2 or python3 code with the given password and can reuse with that password

A tool that can encrypt python2 or python3 code with the given password and can reuse with that password

Pytools is an open source library containing general machine learning and visualisation utilities for reuse
Pytools is an open source library containing general machine learning and visualisation utilities for reuse

pytools is an open source library containing general machine learning and visualisation utilities for reuse, including: Basic tools for API developmen

split-manga-pages: a command line utility written in Python that converts your double-page layout manga to single-page layout.

split-manga-pages split-manga-pages is a command line utility written in Python that converts your double-page layout manga (or any images in double p

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is su

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is su

Page to PAGE Layout Analysis Tool

P2PaLA Page to PAGE Layout Analysis (P2PaLA) is a toolkit for Document Layout Analysis based on Neural Networks. 💥 Try our new DEMO for online baseli

PAGE XML format collection for document image page content and more
PAGE XML format collection for document image page content and more

PAGE-XML PAGE XML format collection for document image page content and more For an introduction, please see the following publication: http://www.pri

Django-Text-to-HTML-converter - The simple Text to HTML Converter using Django framework

Django-Text-to-HTML-converter This is the simple Text to HTML Converter using Dj

A Django app that allows you to send email asynchronously in Django. Supports HTML email, database backed templates and logging.

Django Post Office Django Post Office is a simple app to send and manage your emails in Django. Some awesome features are: Allows you to send email as

Easy and free contact form on your HTML page. No backend or JS required.

Easy and free contact form on your HTML page. No backend or JS required. 🚀 💬

A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication. For use with cookiecutter.
A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication. For use with cookiecutter.

cookiecutter-flask A Flask template for cookiecutter. (Supports Python ≥ 3.6) See this repo for an example project generated from the most recent vers

This is a template tag project for django to calculate in templates , enjoy it

Calculator-Template-Django this is a template tag project for django to calculate in templates , enjoy it Get Started : 1 - Download Source Code 2 - M

Jinja is a fast, expressive, extensible templating engine.

Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template allow writing code similar to Python syntax.

Automatizando a criação de DAGs usando Jinja e YAML

Automatizando a criação de DAGs no Airflow usando Jinja e YAML Arquitetura do Repo: Pastas por contexto de negócio (ex: Marketing, Analytics, HR, etc)

Comments
  • Make package framework-agnostic; add FastAPI/Starlette support

    Make package framework-agnostic; add FastAPI/Starlette support

    @mikeckennedy When I was watching HTMX + Flask course, I decided to do it using FastAPI (love it too much). Your library was heavily dependant on Flask, this PR solves it.

    I hadn't have time to test yet is will this work with FastAPI or Flask without each other 😅 And also didn't test on Python <3.10

    • [x] Test with FastAPI without Flask and vise versa
    • [x] Test on Python <3.10
    • [x] Add example to README.md

    Also I fixed this deprecation warning:

    .../jinja_partials/jinja_partials/__init__.py:52: DeprecationWarning: 'jinja2.Markup' is deprecated and will be removed in Jinja 3.1. Import 'markupsafe.Markup' instead.
        return Markup(renderer(template_name, **data))
    
    opened by vrslev 7
  • Automatically add request to context if it's present.

    Automatically add request to context if it's present.

    Passing request to render_partial seems like a frequent pattern, at least in my usecases where I generate links using url_for(). Maybe I'm doing something wrong :wink: It would be great if the request was passed automatically.

    opened by dekoza 1
  • Without Flask

    Without Flask

    Hello, I'm working with a number to html templates which need to be used both online and offline. Is there anyway for this library to work in html outside of Flask? Thank you

    opened by Snicker7 4
  • Bottlepy

    Bottlepy

    Is there scope to get this working on bottlepy? My normal stack jinja2 templating in Bottle. I'm half way through the htmx course which is pretty neat and wanted to see if I could get this to work. Cheers

    opened by benboughton1 1
Owner
Michael Kennedy
A Python and MongoDB enthusiast, and an entrepreneur. Host of @talkpython and pythonbytes, founder of Talk Python Training. Python Software Foundation Fellow.
Michael Kennedy
✈️ HTML Template engine for python. Supports XSS preventation and many more!

Htmotor HTML Template Engine for Python! Installation: Open your terminal and type pip install htmotor.

Penguen 3 Nov 6, 2022
A string template language hosted by Python3 runtime

A string template language hosted by Python3 runtime. Conventionally, the source code of this language is written in plain text with utf-8 encoding and stored in a file with extension ".meme".

null 6 Nov 2, 2022
A simple, elegant Python based web templating engine (part of web.py).

Templator Simple, elegant Python based web templating (part of web.py). If you are familiar with Python, there is no new syntax to learn. This is a st

Dan 1 Dec 13, 2021
Use a docx as a jinja2 template

Use a docx as a jinja2 template

Eric Lapouyade 1.4k Jan 2, 2023
A general purpose template driven code generator

?? Shit Mountain Generator A general purpose template driven code generator Contribute shits to your company's shit mountain more efficiently! Quick S

Kelly 14 Mar 9, 2022
HTML Template Linter and Formatter. Use with Django, Jinja, Nunjucks and Handlebars templates.

Find common formatting issues and reformat HTML templates. Django · Jinja · Nunjucks · Handlebars · Mustache · GoLang Ps, --check it out on other temp

Riverside Healthcare Analytics 263 Jan 1, 2023
A HTML-code compiler-thing that lets you reuse HTML code.

RHTML RHTML stands for Reusable-Hyper-Text-Markup-Language, and is pronounced "Rech-tee-em-el" despite how its abbreviation is. As the name stands, RH

Duckie 4 Nov 15, 2021
Use heroicons in your Django and Jinja templates.

heroicons Use heroicons in your Django and Jinja templates. Requirements Python 3.6 to 3.9 supported. Django 2.2 to 3.2 supported. Are your tests slow

Adam Johnson 52 Dec 14, 2022
JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates.

JTEX JTEX is a command line tool (CLI) for rendering LaTeX documents from jinja-style templates. This package uses Jinja2 as the template engine with

Curvenote 15 Dec 21, 2022
Django/Jinja template indenter

DjHTML A pure-Python Django/Jinja template indenter without dependencies. DjHTML is a fully automatic template indenter that works with mixed HTML/CSS

Return to the Source 378 Jan 1, 2023