• Stars
    star
    191
  • Rank 202,877 (Top 4 %)
  • Language
    Python
  • License
    MIT License
  • Created over 3 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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)
# ...

You can also use this library in your FastAPI (or Starlette) project!

from fastapi.templating import Jinja2Templates
# or `from starlette.templating import Jinja2Templates`

import jinja_partials

templates = Jinja2Templates("tests/test_templates")

jinja_partials.register_starlette_extensions(templates)
# ...

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:

<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) }} views</div>
</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:

{% 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.

Why not just use include or macro from Jinja?

The short answer is they are nearly the same, but both fall short in different ways. For a more detailed response, see the discussion on issue #1

More Repositories

1

python-jumpstart-course-demos

Contains all the "handout" materials for my Python Jumpstart by Building 10 Apps course. This includes try it yourself and finished versions of the 10 apps.
Python
746
star
2

write-pythonic-code-demos

Write Pythonic Code Like a Seasoned Developer video course demo materials.
Python
727
star
3

mongodb-quickstart-course

Course demos and handout material for Talk Python's MongoDB Quickstart course
Python
306
star
4

python-for-entrepreneurs-course-demos

Contains all the "handout" materials for Talk Python's Python for Entrepreneurs course. This includes notes and the final version of the website code.
Python
286
star
5

python-switch

Adds switch blocks to Python #pypackage
Python
247
star
6

mongodb-for-python-developers

MongoDB for Python developers course handouts from Talk Python Training
Python
176
star
7

talk-python-transcripts

Transcripts for the Talk Python To Me episodes
145
star
8

fastapi-chameleon

Adds integration of the Chameleon template language to FastAPI. #pypackage
Python
139
star
9

async-await-jetbrains-webcast

Python
127
star
10

pyscript-pwa-example

JavaScript
106
star
11

ten-tips-for-pythonic-code-jetbrains-webcast

JetBrains / PyCharm webinar: 10 Tips for Pythonic Code by Michael Kennedy
Python
101
star
12

consuming_services_python_demos

Consuming HTTP and SOAP services in Python course handouts
Python
96
star
13

cookiecutter-course

Handout materials for our course on CookieCutter at Talk Python Training
Python
72
star
14

cookiecutter-pyramid-talk-python-starter

An opinionated Cookiecutter template for creating Pyramid web applications starting way further down the development chain. This cookiecutter template will create a new Pyramid web application with email, sqlalchemy, rollbar, and way more integrated.
Python
67
star
15

markdown-subtemplate

A template engine to render Markdown with external template imports and basic variable replacements. #pypackage
Python
63
star
16

restful-services-in-pyramid

RESTful / HTTP services in Pyramid and Python course handout materials
Python
58
star
17

umami-python

Umami Analytics Client for Python
Python
58
star
18

urlify

A simple macOS app to create valid file and url names from clipboard text. #pypackage
Python
52
star
19

write-pythonic-code-for-better-data-science-webcast

Python
41
star
20

python_bytes_show_notes

Show notes from the Python Bytes podcast
Python
40
star
21

cache-tier

Imagine you have a set of static files you want to serve to the world. Cache-tier allows you to quickly spin up a Linux web server in a location with cheap, plentiful bandwidth and serve those files to your users.
Python
31
star
22

ten-tips-python-web-devs

Repo for topics covered during the presentation
JavaScript
30
star
23

python-shorts

Learn Python tips, tools, and techniques in around 5 minutes each.
Python
30
star
24

pycon-sk-pythonic-talk

Python
29
star
25

docker-build-fastapi-app-april-2021

Python
27
star
26

jetbrains-webcast-build-with-mongodb

Code and handouts for my JetBrains webcast recorded January 30, 2018
Python
26
star
27

improve-mvc-perf-with-async-views

C#
25
star
28

pythons-gc-and-orms

A simple project to explore the number of GCs when doing basic ORM work.
Python
25
star
29

mongodb-query-helper-for-dotnet

C#
24
star
30

streamdeck-developer-profiles

A set of profiles for Elgato's Stream Deck aimed at programming tools
24
star
31

mastering-pycharm-course

Course demos and handouts for Talk Python's Mastering PyCharm course
24
star
32

listmonk

Listmonk Email App API Client for Python
Python
24
star
33

build-pypi-mongodb-webcast-series

Code demos and hand-outs for my webcast series with MongoDB (May - June 2018)
Python
22
star
34

optimistic_concurrency_mongodb_dotnet

This c# library adds optimistic concurrency control to MongoDB and acts as a MongoDB ORM foundation.
C#
20
star
35

chameleon_partials

Simple reuse of partial HTML page templates in the Chameleon template language for Python web frameworks. #pypackage
Python
14
star
36

server-hot-reload

Include in your web projects for dev-time auto reloading of web browser when any change is detected in content.
JavaScript
13
star
37

wakeup

A little Python app to make sure your server is warmed up
Python
10
star
38

pycon-sk-mongodb-workshop

Python
7
star
39

pyramid-web-builder-python-gui

Python
6
star
40

EssentialPythonDemos

Essential Python Demos
6
star
41

python-mongodb-intro-jetbrains-webcast

Demo code for my webcast on MongoDB hosted by the PyCharm team
6
star
42

managed_system_hooks

The class library can be used to create any type of system hook. There are two that come pre-built: MouseHook and KeyboardHook. We have also included specialized versions of these classes called MouseHookExt and KeyboardHookExt respectively. Following the model set by those classes, you can easily build system hooks for any of the 15 hook event types in the Win32 API. Also, the entire class library comes with a compiled HTML help file which documents the classes. Be sure to look at this help file if you decide to use this library in your applications.
C#
6
star
43

web-apps-hotkeys

C#
5
star
44

write-pythonic-code-va-meetup

Python
4
star
45

pyramid-cookiecutter-starter-chameleon

Python
4
star
46

windows-python-compatibility-pack

A few commands to make the command prompt identical with macOS and Linux terminals
Batchfile
4
star
47

tinydb-sample-blog

A (very) simple demo app using TinyDb
Python
4
star
48

python-virtual-conf-web-tips

Code and demos from my Python Virtual Conference 2020 talk
Python
4
star
49

fastapi-twitch-examples

Python
4
star
50

talk-python-search-service

An open-source adaption of the high perf search engine powering Talk Python's web properties
Python
3
star
51

enhanced_aspnet_mvc_views

Enhanced View Locations for MVC allows you to further organize your ASP.NET MVC views without your action methods or Html.RenderPartial / Html.RenderAction elements knowing or caring about how they are organized or re-organized.
C#
3
star
52

funny-web

Sample repo for funny web app, featured in Up and Running with Git course.
Python
2
star
53

jetbrains-git-webcast-2022

Python
2
star
54

asq

Automatically exported from code.google.com/p/asq
Python
2
star
55

sketchy-rock-paper-scissors

Sample repo for Rock Paper Scissors app, featured in Up and Running with Git course.
Python
2
star
56

text-encoding-aspnet-mvc-by-example

CSS
2
star
57

python-for-dotnet-devs-ndc-oslo-2016

Live demo materials from my session at NDC Olso 2016.
Python
1
star
58

python-data-driven-nov9

Python
1
star
59

DevWeek2015

C#
1
star
60

suds_python

Python
1
star
61

asq.docs

Automatically exported from code.google.com/p/asq.docs
HTML
1
star
62

portland-state-data-sci

Jupyter Notebook
1
star
63

SDDConf2015

C#
1
star
64

python_workshop_demos_april_2018

1
star
65

smarter_web_deploy

A library to extend Microsoft's Web Deploy feature in Visual Studio to create reliable and fast deploys on production sites running on IIS and Windows Servers.
C#
1
star