.. image:: https://img.shields.io/travis/edoburu/django-tag-parser/master.svg?branch=master
:target: http://travis-ci.org/edoburu/django-tag-parser
.. image:: https://img.shields.io/pypi/v/django-tag-parser.svg
:target: https://pypi.python.org/pypi/django-tag-parser/
.. image:: https://img.shields.io/pypi/l/django-tag-parser.svg
:target: https://pypi.python.org/pypi/django-tag-parser/
.. image:: https://img.shields.io/codecov/c/github/edoburu/django-tag-parser/master.svg
:target: https://codecov.io/github/edoburu/django-tag-parser?branch=master
django-tag-parser
=================
A micro-library to easily write custom Django template tags.
Features:
* Functions to parse tags, especially: "args", "kwargs", and "as varname" syntax.
* Real OOP classes to write custom inclusion tags.
Functions:
* ``parse_token_kwargs``: split a token into the tag name, args and kwargs.
* ``parse_as_var``: extract the "as varname" from a token.
Base classes (in ``tag_parser.basetags``):
* ``BaseNode``: A template ``Node`` object which features some basic parsing abilities.
* ``BaseInclusionNode``: a ``Node`` that has ``inclusion_tag`` like behaviour, but allows to override the ``template_name`` dynamically.
* ``BaseAssignmentNode``: a ``Node`` that returns the value in the context, using the ``as var`` syntax.
* ``BaseAssignmentOrOutputNode``: a ``Node`` that either displays the value, or inserts it in the context.
* ``BaseAssignmentOrInclusionNode``: a class that allows a ``{% get_items template="..." %}`` and ``{% get_items as var %}`` syntax.
The base classes allows to implement ``@register.simple_tag``, ``@register.inclusion_tag`` and ``@register.assignment_tag`` like functionalities,
while still leaving room to extend the parsing, rendering or syntax validation.
For example, not all arguments need to be seen as template variables, filters or literal keywords.
As of v3.0, the ``@template_tag`` decorator is no longer needed.
Use ``@register.tag("name")`` directly on the class names.
Installation
============
First install the module, preferably in a virtual environment. It can be installed from PyPI:
.. code-block:: bash
pip install django-tag-parser
Examples
========
At the top of your template tags library, always include the standard
Django ``register`` variable and our ``template_tag`` decorator:
.. code-block:: python
from django.template import Library
from tag_parser import template_tag
register = Library()
Arguments and keyword arguments
-------------------------------
To parse a syntax like:
.. code-block:: html+django
{% my_tag "arg1" keyword1="bar" keyword2="foo" %}
use:
.. code-block:: python
from django.template import Library
from tag_parser.basetags import BaseNode
register = Library()
@register.tag('my_tag')
class MyTagNode(BaseNode):
max_args = 1
allowed_kwargs = ('keyword1', 'keyword2',)
def render_tag(self, context, *tag_args, **tag_kwargs):
return "Tag Output"
Inclusion tags
--------------
To create an inclusion tag with overwritable template_name:
.. code-block:: html+django
{% my_include_tag "foo" template="custom/example.html" %}
use:
.. code-block:: python
from django.template import Library
from tag_parser.basetags import BaseInclusionNode
register = Library()
@register.tag("my_include_tag")
class MyIncludeTag(BaseInclusionNode):
template_name = "mytags/default.html"
max_args = 1
def get_context_data(self, parent_context, *tag_args, **tag_kwargs):
(foo,) = *tag_args
return {
'foo': foo
}
The ``get_template_name()`` method can be overwritten too to support dynamic resolving of template names.
By default it checks the ``template`` tag_kwarg, and ``template_name`` attribute.
Note the template nodes are cached afterwards, it's not possible to return random templates at each call.
Assignment tags
---------------
To create assignment tags that can either render itself, or return context data:
.. code-block:: html+django
{% get_tags template="custom/example.html" %}
{% get_tags as popular_tags %}
use:
.. code-block:: python
from django.template import Library
from tag_parser.basetags import BaseAssignmentOrInclusionNode
register = Library()
@register.tag('get_tags')
class GetPopularTagsNode(BaseAssignmentOrInclusionNode):
template_name = "myblog/templatetags/popular_tags.html"
context_value_name = 'tags'
allowed_kwargs = (
'order', 'orderby', 'limit',
)
def get_value(self, context, *tag_args, **tag_kwargs):
return query_tags(**tag_kwargs) # Something that reads the tags.
Block tags
----------
To have a "begin .. end" block, define ``end_tag_name`` in the class:
.. code-block:: html+django
{% my_tag keyword1=foo %}
Tag contents, possibly other tags.
{% end_my_tag %}
use:
.. code-block:: python
from django.template import Library
from tag_parser.basetags import BaseAssignmentOrInclusionNode
register = Library()
@register.tag('my_tag')
class MyTagNode(BaseNode):
max_args = 1
allowed_kwargs = ('keyword1', 'keyword2',)
end_tag_name = 'end_my_tag'
def render_tag(self, context, *tag_args, **tag_kwargs):
# Render contents inside
return self.nodelist.render(context)
Custom parsing
--------------
With the standard ``Node`` class from Django, it's easier to implement custom syntax.
For example, to parse:
.. code-block:: html+django
{% getfirstof val1 val2 as val3 %}
use:
.. code-block:: python
from django.template import Library, Node, TemplateSyntaxError
from tag_parser import parse_token_kwargs, parse_as_var
register = Library()
@register.tag('getfirstof')
class GetFirstOfNode(Node):
def __init__(self, options, as_var):
self.options = options # list of FilterExpression nodes.
self.as_var = as_var
@classmethod
def parse(cls, parser, token):
bits, as_var = parse_as_var(parser, token)
tag_name, options, _ = parse_token_kwargs(parser, bits, allowed_kwargs=())
if as_var is None or not choices:
raise TemplateSyntaxError("Expected syntax: {{% {0} val1 val2 as val %}}".format(tag_name))
return cls(options, as_var)
def render(self, context):
value = None
for filterexpr in self.options:
# The ignore_failures argument prevents that the value becomes TEMPLATE_STRING_IF_INVALID.
value = filterexpr.resolve(context, ignore_failures=True)
if value is not None:
break
context[self.as_var] = value
return ''
Contributing
------------
This module is designed to be generic. In case there is anything you didn't like about it,
or think it's not flexible enough, please let us know. We'd love to improve it!
If you have any other valuable contribution, suggestion or idea,
please let us know as well because we will look into it.
Pull requests are welcome too. :-)
Raw data
{
"_id": null,
"home_page": "https://github.com/edoburu/django-tag-parser",
"name": "django-tag-parser",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "",
"author": "Diederik van der Boor",
"author_email": "opensource@edoburu.nl",
"download_url": "https://files.pythonhosted.org/packages/30/54/42caebce5b09aa8e630c088eed06e58e287f51845b08bef276cd618e4933/django-tag-parser-3.2.tar.gz",
"platform": "",
"description": ".. image:: https://img.shields.io/travis/edoburu/django-tag-parser/master.svg?branch=master\n :target: http://travis-ci.org/edoburu/django-tag-parser\n.. image:: https://img.shields.io/pypi/v/django-tag-parser.svg\n :target: https://pypi.python.org/pypi/django-tag-parser/\n.. image:: https://img.shields.io/pypi/l/django-tag-parser.svg\n :target: https://pypi.python.org/pypi/django-tag-parser/\n.. image:: https://img.shields.io/codecov/c/github/edoburu/django-tag-parser/master.svg\n :target: https://codecov.io/github/edoburu/django-tag-parser?branch=master\n\ndjango-tag-parser\n=================\n\nA micro-library to easily write custom Django template tags.\n\nFeatures:\n\n* Functions to parse tags, especially: \"args\", \"kwargs\", and \"as varname\" syntax.\n* Real OOP classes to write custom inclusion tags.\n\nFunctions:\n\n* ``parse_token_kwargs``: split a token into the tag name, args and kwargs.\n* ``parse_as_var``: extract the \"as varname\" from a token.\n\nBase classes (in ``tag_parser.basetags``):\n\n* ``BaseNode``: A template ``Node`` object which features some basic parsing abilities.\n* ``BaseInclusionNode``: a ``Node`` that has ``inclusion_tag`` like behaviour, but allows to override the ``template_name`` dynamically.\n* ``BaseAssignmentNode``: a ``Node`` that returns the value in the context, using the ``as var`` syntax.\n* ``BaseAssignmentOrOutputNode``: a ``Node`` that either displays the value, or inserts it in the context.\n* ``BaseAssignmentOrInclusionNode``: a class that allows a ``{% get_items template=\"...\" %}`` and ``{% get_items as var %}`` syntax.\n\nThe base classes allows to implement ``@register.simple_tag``, ``@register.inclusion_tag`` and ``@register.assignment_tag`` like functionalities,\nwhile still leaving room to extend the parsing, rendering or syntax validation.\nFor example, not all arguments need to be seen as template variables, filters or literal keywords.\n\nAs of v3.0, the ``@template_tag`` decorator is no longer needed.\nUse ``@register.tag(\"name\")`` directly on the class names.\n\n\nInstallation\n============\n\nFirst install the module, preferably in a virtual environment. It can be installed from PyPI:\n\n.. code-block:: bash\n\n pip install django-tag-parser\n\n\nExamples\n========\n\nAt the top of your template tags library, always include the standard\nDjango ``register`` variable and our ``template_tag`` decorator:\n\n.. code-block:: python\n\n from django.template import Library\n from tag_parser import template_tag\n\n register = Library()\n\nArguments and keyword arguments\n-------------------------------\n\nTo parse a syntax like:\n\n.. code-block:: html+django\n\n {% my_tag \"arg1\" keyword1=\"bar\" keyword2=\"foo\" %}\n\nuse:\n\n.. code-block:: python\n\n from django.template import Library\n from tag_parser.basetags import BaseNode\n\n register = Library()\n\n\n @register.tag('my_tag')\n class MyTagNode(BaseNode):\n max_args = 1\n allowed_kwargs = ('keyword1', 'keyword2',)\n\n def render_tag(self, context, *tag_args, **tag_kwargs):\n return \"Tag Output\"\n\nInclusion tags\n--------------\n\nTo create an inclusion tag with overwritable template_name:\n\n.. code-block:: html+django\n\n {% my_include_tag \"foo\" template=\"custom/example.html\" %}\n\nuse:\n\n.. code-block:: python\n\n from django.template import Library\n from tag_parser.basetags import BaseInclusionNode\n\n register = Library()\n\n @register.tag(\"my_include_tag\")\n class MyIncludeTag(BaseInclusionNode):\n template_name = \"mytags/default.html\"\n max_args = 1\n\n def get_context_data(self, parent_context, *tag_args, **tag_kwargs):\n (foo,) = *tag_args\n return {\n 'foo': foo\n }\n\nThe ``get_template_name()`` method can be overwritten too to support dynamic resolving of template names.\nBy default it checks the ``template`` tag_kwarg, and ``template_name`` attribute.\nNote the template nodes are cached afterwards, it's not possible to return random templates at each call.\n\n\nAssignment tags\n---------------\n\nTo create assignment tags that can either render itself, or return context data:\n\n.. code-block:: html+django\n\n {% get_tags template=\"custom/example.html\" %}\n {% get_tags as popular_tags %}\n\nuse:\n\n.. code-block:: python\n\n from django.template import Library\n from tag_parser.basetags import BaseAssignmentOrInclusionNode\n\n register = Library()\n\n\n @register.tag('get_tags')\n class GetPopularTagsNode(BaseAssignmentOrInclusionNode):\n template_name = \"myblog/templatetags/popular_tags.html\"\n context_value_name = 'tags'\n allowed_kwargs = (\n 'order', 'orderby', 'limit',\n )\n\n def get_value(self, context, *tag_args, **tag_kwargs):\n return query_tags(**tag_kwargs) # Something that reads the tags.\n\n\nBlock tags\n----------\n\nTo have a \"begin .. end\" block, define ``end_tag_name`` in the class:\n\n.. code-block:: html+django\n\n {% my_tag keyword1=foo %}\n Tag contents, possibly other tags.\n {% end_my_tag %}\n\nuse:\n\n.. code-block:: python\n\n from django.template import Library\n from tag_parser.basetags import BaseAssignmentOrInclusionNode\n\n register = Library()\n\n\n @register.tag('my_tag')\n class MyTagNode(BaseNode):\n max_args = 1\n allowed_kwargs = ('keyword1', 'keyword2',)\n end_tag_name = 'end_my_tag'\n\n def render_tag(self, context, *tag_args, **tag_kwargs):\n # Render contents inside\n return self.nodelist.render(context)\n\n\nCustom parsing\n--------------\n\nWith the standard ``Node`` class from Django, it's easier to implement custom syntax.\nFor example, to parse:\n\n.. code-block:: html+django\n\n {% getfirstof val1 val2 as val3 %}\n\nuse:\n\n.. code-block:: python\n\n from django.template import Library, Node, TemplateSyntaxError\n from tag_parser import parse_token_kwargs, parse_as_var\n\n register = Library()\n\n\n @register.tag('getfirstof')\n class GetFirstOfNode(Node):\n def __init__(self, options, as_var):\n self.options = options # list of FilterExpression nodes.\n self.as_var = as_var\n\n @classmethod\n def parse(cls, parser, token):\n bits, as_var = parse_as_var(parser, token)\n tag_name, options, _ = parse_token_kwargs(parser, bits, allowed_kwargs=())\n\n if as_var is None or not choices:\n raise TemplateSyntaxError(\"Expected syntax: {{% {0} val1 val2 as val %}}\".format(tag_name))\n\n return cls(options, as_var)\n\n def render(self, context):\n value = None\n for filterexpr in self.options:\n # The ignore_failures argument prevents that the value becomes TEMPLATE_STRING_IF_INVALID.\n value = filterexpr.resolve(context, ignore_failures=True)\n if value is not None:\n break\n\n context[self.as_var] = value\n return ''\n\n\n\nContributing\n------------\n\nThis module is designed to be generic. In case there is anything you didn't like about it,\nor think it's not flexible enough, please let us know. We'd love to improve it!\n\nIf you have any other valuable contribution, suggestion or idea,\nplease let us know as well because we will look into it.\nPull requests are welcome too. :-)\n\n\n",
"bugtrack_url": null,
"license": "Apache 2.0",
"summary": "Micro-library to easily write custom Django template tags",
"version": "3.2",
"project_urls": {
"Download": "https://github.com/edoburu/django-tag-parser/zipball/master",
"Homepage": "https://github.com/edoburu/django-tag-parser"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "167ffedeec26fa0fa27d0d8cd3169894ea447e6bd7ff3a21154ee0d54804661c",
"md5": "3f8e37ea8428d6758e40224417966c10",
"sha256": "92e5da35d8774a6ab4e0ac0b3b2229b8a0b78a61c5a3b0fd159255f0a66c08d7"
},
"downloads": -1,
"filename": "django_tag_parser-3.2-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "3f8e37ea8428d6758e40224417966c10",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 17438,
"upload_time": "2019-12-18T07:47:11",
"upload_time_iso_8601": "2019-12-18T07:47:11.135540Z",
"url": "https://files.pythonhosted.org/packages/16/7f/fedeec26fa0fa27d0d8cd3169894ea447e6bd7ff3a21154ee0d54804661c/django_tag_parser-3.2-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "305442caebce5b09aa8e630c088eed06e58e287f51845b08bef276cd618e4933",
"md5": "4160554fe9beae29ebc86aea67107df0",
"sha256": "903cd4bf3692c8c060770ca2b9d6e74e4ee52d6078308852acffe1ef4a49e0f7"
},
"downloads": -1,
"filename": "django-tag-parser-3.2.tar.gz",
"has_sig": false,
"md5_digest": "4160554fe9beae29ebc86aea67107df0",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 15170,
"upload_time": "2019-12-18T07:47:13",
"upload_time_iso_8601": "2019-12-18T07:47:13.109852Z",
"url": "https://files.pythonhosted.org/packages/30/54/42caebce5b09aa8e630c088eed06e58e287f51845b08bef276cd618e4933/django-tag-parser-3.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2019-12-18 07:47:13",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "edoburu",
"github_project": "django-tag-parser",
"travis_ci": true,
"coveralls": true,
"github_actions": false,
"tox": true,
"lcname": "django-tag-parser"
}