django-template-partials

repository·main·Indexed 20 days ago

https://github.com/carltongibson/django-template-partials

Provides reusable, named inline partials for the Django Template Language. It allows developers to define template fragments using {% partialdef %} and render them via {% partial %}, or target specific partials independently through the template loader or {% include %} tag using the # syntax (e.g., "example.html#test-partial"). The library includes support for inline rendering and context control via the {% with %} tag. Note that these features are integrated into Django Core starting with Django 6.0.

Tokens
2.8K
Snippets
14
Records
16
Agent score
69%

What's inside django-template-partials

  1. Render a partial via the template loader or include tag

    main

    django-template-partials integrates with the Django template loader, allowing you to target a specific partial directly via a string identifier using the # syntax.

    In a View

    You can set self.template_name (or the equivalent in your view) to include the partial name:

    self.template_name = "example.html#test-partial"

    Using the include tag

    You can also include a specific partial from another template using the standard {% include %} tag:

    {% include "example.html#test-partial" %}
    # In view handler
    self.template_name = "example.html#test-partial"
  2. Advanced configuration of the partials template loader

    main

    By default, adding template_partials to INSTALLED_APPS automatically configures all template backends to use the partials loader.

    Using SimpleAppConfig

    If you want to prevent automatic configuration of all backends, use template_partials.apps.SimpleAppConfig in INSTALLED_APPS instead:

    INSTALLED_APPS = [
        "template_partials.apps.SimpleAppConfig",
        ...,
    ]

    Manual configuration with wrap_loaders()

    If you use SimpleAppConfig, you must manually configure the loader for specific backends using the wrap_loaders() function. You can pass the NAME of the template configuration to target a specific backend.

    from template_partials.apps import wrap_loaders
    
    # Assuming 'myname' is the NAME in your TEMPLATES setting
    wrap_loaders("myname")

    If no NAME is provided, wrap_loaders() uses the penultimate element of the BACKEND value (e.g., for django.template.backends.django.DjangoTemplates, the name is django).

    from template_partials.apps import wrap_loaders
    
    wrap_loaders("myname")
  3. Remove template tag loading after migration

    main

    After migrating to Django Core, the partials tag is built-in. You must remove the {% load partials %} statement from your templates. The {% partialdef %} and {% endpartialdef %} tags will continue to function without the explicit load statement.

    <!-- Before migration -->
    {% load partials %}
    {% partialdef my-partial %}
    <!-- content -->
    {% endpartialdef %}
    
    <!-- After migration -->
    {% partialdef my-partial %}
    <!-- content -->
    {% endpartialdef %}
  4. Define and reuse template partials

    main

    To use partials, load the partials tags in your template. You can define a reusable named block using {% partialdef %} and render it later using {% partial %}.

    Defining a partial

    Use {% partialdef name %}. You can optionally include the name in the closing tag for readability: {% endpartialdef name %}.

    Reusing a partial

    Use {% partial name %} to render the content of the defined partial at that location. The partial is rendered with the current template context.

    {% load partials %}
    
    {% partialdef test-partial %}
    TEST-PARTIAL-CONTENT
    {% endpartialdef test-partial %}
    
    {% block main %}
    BEGINNING
    {% partial test-partial %}
    MIDDLE
    {% partial test-partial %}
    END
    {% endblock main %}
  5. Control partial context with the with tag

    main

    Partials are rendered with the current template context. This allows them to work naturally inside loops. If you need to provide specific variables to a partial, use the standard Django {% with %} tag.

    {% for object in object_list %}
        {% partial test-partial %}
    {% endfor %}
    
    {% with name=value othername=othervalue %}
        {% partial test-partial %}
    {% endwith %}
  6. Migrate django-template-partials to Django Core

    main

    When migrating from django-template-partials to Django Core (starting with Django 6.0), follow these steps to remove the library and switch to the built-in functionality. All existing functionality including partialdef, inline partials, and context handling is expected to work with the core implementation.

    1. Remove from INSTALLED_APPS

    Remove "template_partials" or "template_partials.apps.SimpleAppConfig" from your INSTALLED_APPS setting.

    2. Remove Manual TEMPLATES Setting Changes

    If you manually configured the template loader or added partials to builtins, remove those configurations:

    • Remove "template_partials.templatetags.partials" from the builtins list in your TEMPLATES setting.
    • Remove any custom loader configurations, such as loaders = [("template_partials.loader.Loader", cached_loaders)].

    3. Remove Template Tag Loading

    Since partials is now a built-in tag in Django Core, you no longer need to load it manually. Remove {% load partials %} from all your templates.

    4. Uninstall the Package

    Uninstall the package from your environment and remove it from your dependency files (requirements.txt, pyproject.toml, etc.):

    pip uninstall django-template-partials

    Note: Test your templates thoroughly after migration to ensure compatibility with the Django 6.0 implementation.

    # Before migration (example INSTALLED_APPS)
    INSTALLED_APPS = [
        "template_partials",
        "django.contrib.admin",
    ]
    
    # After migration
    INSTALLED_APPS = [
        "django.contrib.admin",
    ]
  7. How the Template Loader works

    main

    The Loader class is a wrapper that integrates with Django's template loading system to enable partials. It takes a list of existing template loaders and attempts to resolve templates from them in order.

    When a template name is requested using the # syntax (e.g., template_name#partial_name), the loader:

    1. Splits the name into the base template_name and the partial_name.
    2. Uses the underlying loaders to find the base template.
    3. If a partial_name was provided, it searches the template for a defined partial with that name.
    4. Returns the partial template object, making partials transparent to the view and response layers.
  8. Automatically load partials tags using builtins

    main

    To avoid adding {% load partials %} to every template, you can add the partials tags to your Django template engine's builtins configuration in settings.py.

    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "OPTIONS": {
                "builtins": [
                    "template_partials.templatetags.partials",
                ],
                ...
            },
        },
        ...
    ]
    OPTIONS = {
        "builtins": ["template_partials.templatetags.partials"],
    }
  9. Syntax for requesting partials

    main

    To request a specific partial from a template, use the # character as a delimiter in the template name string. The format is:

    template_name#partial_name

    If the # character is not present, the loader returns the full template as usual. If the # character is present but the partial_name does not exist within the template, a TemplateDoesNotExist exception is raised.

    # Example of how a template name is parsed internally
    template_name, _, partial_name = "path/to/template.html#my_partial".partition("#")
    # template_name is "path/to/template.html"
    # partial_name is "my_partial"
  10. Configure automatic partials loader setup

    main

    By default, adding template_partials to your INSTALLED_APPS automatically configures the Django template engine to support partials. It does this by wrapping your existing template loaders with template_partials.loader.Loader.

    This automatic configuration modifies your TEMPLATES setting to include the partials loader as a layer over your standard filesystem and app directory loaders.

    # In your settings.py
    INSTALLED_APPS = [
        ...
        "template_partials",
        ...
    ]