Git Product home page Git Product logo

django-viewlet's Introduction

image

Render template parts with extended cache control.

image

image

image

image

Installation

Install django-viewlet in your python environment

$ pip install django-viewlet

Supports Django versions 2.2, 3.2, 4.0 and Python versions 3.7 - 3.9.

Configuration

Add viewlet to your INSTALLED_APPS setting so Django can find the template tag

INSTALLED_APPS = (
    ...,
    "viewlet",
)

Jinja2

Add ViewletExtension to the list of extensions of Jinja2 template engine

TEMPLATES = (
    [
        {
            "BACKEND": "django.template.backends.jinja2.Jinja2",
            # ...
            "OPTIONS": {
                # ...
                "extensions": [
                    # ...
                    "viewlet.loaders.jinja2_loader.ViewletExtension",
                ],
            },
        }
    ],
)

Usage

A viewlet is almost like a function based django view, taking a template context as first argument instead of request. Place your viewlets in viewlets.py or existing views.py in your django app directory.

from django.template.loader import render_to_string
from viewlet import viewlet


@viewlet
def hello_user(context, name):
    return render_to_string("hello_user.html", {"name": name})

You can then render the viewlet with the viewlet template tag:

{% load viewlets %}
<p>{% viewlet hello_user request.user.username %}</p>

... and in your Jinja2 templates:

<p>{% viewlet 'host_sponsors', host.id) %}</p>

Specifying cache backend

By default viewlet will try using viewlet cache alias, falling back to default. You can specify which alias should be used in settings:

VIEWLET_DEFAULT_CACHE_ALIAS = "template_cache"

CACHES = {
    # ...
    "template_cache": {
        # ...
    },
    # ...
}

Additionally, you can override cache alias in viewlet decorator with using argument

@viewlet(using="super_cache")
def hello_user(context, name):
    return render_to_string("hello_user.html", {"name": name})

Refreshing viewlets

A cached viewlet can be re-rendered and updated behind the scenes with viewlet.refresh

import viewlet

viewlet.refresh("hello_user", "monkey")
# or
hello_user.refresh("monkey")

The decorator

@viewlet(name, template, key, timeout)
def my_viewlet():
    ...
  • name

    Optional reference name for the viewlet, defaults to function name.

  • template

    Optional path to template. If specified the viewlet must return a context dict, otherwise it is responsible to return the rendered output itself.

  • key

    Optional cache key, if not specified a dynamic key will be generated viewlet:name(args...)

  • timeout

    Cache timeout. Defaults to configured cache backend default timeout, None = eternal, 0 = uncached.

Examples

The content returned by the viewlet will by default be cached. Use the timeout argument to change this.

@viewlet(timeout=30 * 60)
def hello_user(context, name):
    return render_to_string("hello_user.html", {"name": name})

Django viewlet will by default build a cache key viewlet:name(args...). To customize this key pass a string to the viewlet decorator argument key that includes string mod operators for each viewlet argument.

@viewlet(timeout=30 * 60, key="some_cache_key_%s")
def hello_user(context, name):
    return render_to_string("hello_user.html", {"name": name})

Django viewlet will cache returned context instead of html by using the template decorator argument. This is useful if cached html is too heavy, or your viewlet template needs to be rendered on every call. The specified template will then be rendered with the viewlet context merged with the parent context, usually a RequestContext.

@viewlet(template="hello_user.html", timeout=30 * 60)
def hello_user(context, name):
    return {"name": name}

If there is no need for caching, set the viewlet decorator argument timeout to 0.

@viewlet(timeout=0)
def hello_user(context, name):
    return render_to_string("hello_user.html", {"name": name})

By default your viewlets will be named as the function. To override this you can set the decorator argument name

@viewlet(name="greeting")
def hello_user(context, name):
    return render_to_string("hello_user.html", {"name": name})

A powerful usage of viewlet.refresh is to use it together with Django signals:

class Product(Model):
    name = CharField(max_length=255)


@viewlet(timeout=None)
def product_teaser(context, id):
    product = get_context_object(Product, id, context)
    return render_to_string("product_teaser.html", locals())


def refresh_product_teaser(instance, **kwargs):
    viewlet.refresh("product_teaser", instance.id)


post_save.connect(refresh_product_teaser, Product)

Viewlets can also be accesses with AJAX by adding viewlet.urls to your Django root urls:

urlpatterns = patterns(
    "",
    (r"^viewlet/", include("viewlet.urls")),
)

The url ends with the viewlet name followed by a querystring used as kwargs to the viewlet:

django-viewlet's People

Contributors

andreif avatar beshrkayali avatar chrippa avatar gardeman avatar hannseman avatar heyman avatar idealatom avatar lundberg avatar mojken avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-viewlet's Issues

Error in readme regarding VIEWLET_JINJA2_ENVIRONMENT

When using jingo the env should be configured to:

VIEWLET_JINJA2_ENVIRONMENT = 'jingo.env'
NOT
VIEWLET_JINJA2_ENVIRONMENT = 'jingo.get_env'

otherwise all the jingo helpers won't be accessible from within the viewlet's templates

Refreshing context viewlets using jinja templates and extra context breaks

When calling viewlet.refresh() on a context viewlet; that triggers the whole rendering process, which causes rendering of jinja2-templates to raise if the template expects extra context variables not given by the viewlet itself.

To fix this the refresh function no longer may return the actual rendered viewlet.
Is this a problem API wise?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.