Extra tags an filters for python-liquid.
Project description
A growing collection of extra tags and filters for Python Liquid.
Extra Tags
Extra Filters
Installing
Install and update using pip:
$ python -m pip install -U python-liquid-extra
Usage
All filters and tags built-in to Liquid are registered automatically when you create a new Environment. If you register a new tag or filter with the same name as a built-in one, the built-in tag or filter will be replaced without warning.
Filters
Register a filter by calling the add_filter method of a liquid.Environment. add_filter takes two arguments. The first is the filter’s name. This is what you’ll use to apply the filter to an expression in a liquid template. The second is any callable that accepts at least one argument, the result of the left hand side of the expression the filter is applied to.
add_filter(name: str, filter_: Callable[..., Any]) -> None
For example
from liquid import Environment
from liquid_extra import filters
env = Environment()
env.add_filter("json", filters.JSON())
Or, if you’re using Flask-Liquid.
# saved as app.py
from flask import Flask
from flask_liquid import Liquid
from flask_liquid import render_template
from liquid_extra import filters
app = Flask(__name__)
liquid = Liquid(app)
liquid.env.add_filter("json", filters.JSON())
@app.route("/hello/")
@app.route("/hello/<name>")
def index(name=None):
return render_template("index.html", name=name)
Equivalently, using django-liquid, if the following is saved as myproject/liquid.py
from liquid import Environment
from liquid_extra import filters
def environment(**options):
env = Environment(**options)
env.add_filter("json", filters.JSON())
# Register more filters or tags here.
return env
Then tell the django template backend to use your environment factory function in your project’s settings.py file.
TEMPLATES = [
{
'BACKEND': 'django_liquid.liquid.Liquid',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'myproject.liquid.environment'
},
},
]
Filters can be implemented as simple functions, classes with a __call__ method or closures that return a function or callable object. The latter two could take additional arguments, some optional and some mandatory. Refer to the documentation for each filter below to see what, if any, additional arguments they support.
Extra Filters
index
Return the first zero-based index of an item in an array. Or None if the item is not in the array.
from liquid import Environment
from liquid_extra import filters
env = Environment()
env.add_filter("index", filters.index)
template = env.from_string("{{ colours | index 'blue' }}")
context = {
"colours": ["red", "blue", "green"],
}
print(template.render(**context)) # 1
json
Serialize objects as a JSON (JavaScript Object Notation) formatted string.
The json filter uses Python’s default JSONEncoder, supporting dict, list, tuple, str, int, float, some Enums, True, False and None.
from liquid import Environment
from liquid_extra import filters
env = Environment()
env.add_filter("json", filters.JSON())
template = env.from_string("""
<script type="application/json">
{{ product | json }}
</script>
""")
context = {
"product": {
"id": 1234,
"name": "Football",
},
}
print(template.render(**context))
<script type="application/json">
{"product": {"id": 1234, "name": "Football"}}
</script>
The JSON filter takes an optional default argument. default will be passed to json.dumps and should be a function that gets called for objects that can’t otherwise be serialized. For example, this default function adds support for serializing data classes.
from dataclasses import dataclass
from dataclasses import asdict
from dataclasses import is_dataclass
from liquid import Environment
from liquid_extra import filters
env = Environment()
def default(obj):
if is_dataclass(obj):
return asdict(obj)
env.add_filter("json", filters.JSON(default=default))
template = env.from_string("""
<script type="application/json">
{{ product | json }}
</script>
""")
@dataclass
class Product:
id: int
name: str
print(template.render(product=Product(1234, "Football")))
stylesheet_tag
Wrap a URL in an HTML stylesheet tag.
from liquid import Environment
from liquid_extra import filters
env = Environment()
env.add_filter("stylesheet_tag", filters.stylesheet_tag)
template = env.from_string("{{ url | stylesheet_tag }}")
context = {
"url": "https://example.com/static/style.css",
}
print(template.render(**context))
<link href="https://example.com/static/style.css" rel="stylesheet" type="text/css" media="all" />
script_tag
Wrap a URL in an HTML script tag.
from liquid import Environment
from liquid_extra import filters
env = Environment()
env.add_filter("script_tag", filters.script_tag)
template = env.from_string("{{ url | script_tag }}")
context = {
"url": "https://example.com/static/app.js",
}
print(template.render(**context))
<script src="https://example.com/static/app.js" type="text/javascript"></script>
t (translate)
Replace translation keys with strings for the current locale.
Pass a mapping of locales to translations to the Translate filter when you register it with a liquid.Environment. The current locale is read from the template context at render time.
from liquid import Environment
from liquid_extra.filters import Translate
some_locales = {
"default": {
"layout": {
"greeting": r"Hello {{ name }}",
},
"cart": {
"general": {
"title": "Shopping Basket",
},
},
"pagination": {
"next": "Next Page",
},
},
"de": {
"layout": {
"greeting": r"Hallo {{ name }}",
},
"cart": {
"general": {
"title": "Warenkorb",
},
},
"pagination": {
"next": "Nächste Seite",
},
},
}
env = Environment()
env.add_filter(Translate.name, Translate(locales=some_locales))
template = env.from_string("{{ 'layout.greeting' | t: name: user.name }}")
# Defaults to the "default" locale.
print(template.render(user={"name": "World"})) # -> "Hello World"
# Use the "locale" context key to specify the current locale.
print(template.render(locale="de", user={"name": "Welt"})) # -> "Hallo Welt"
Notice that the t filter accepts arbitrary named parameters. Named parameters can be used to substitute fields in translation strings with values from the template context.
It you don’t give Translate any locales or you leave it empty, you’ll always get the translation key back unchanged.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for python-liquid-extra-0.3.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | eccb5ee47b14e348c70a78d2ecce26c1ffe075893b5393251aeecc4c4d5d496a |
|
MD5 | b95ab09663022d61ce868dcbd9bdf9d3 |
|
BLAKE2b-256 | ab613e8d9d9d2f2337cfed1ab7436397218bc84c69b90558789dc46d27b7cb79 |
Hashes for python_liquid_extra-0.3.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ef672d2ba2ef1bcecefa6d7be2dfe2306addf6cabc150a5e2a8ab329ebe39860 |
|
MD5 | 313004cb46c82d12989526423b933295 |
|
BLAKE2b-256 | 7256ddfc4cfeee1ad1d49d582bd84b058fb0d12c441bd8561973ad2e5358b59b |