Skip to content

Add support for rendering patterns over an API endpoint #104

Closed
@thibaudcolas

Description

@thibaudcolas

Needed for #103. The Storybook integration relies on the following API view:

https://github.com/torchbox/storybook-django/blob/8a62a8bc6fabbc25ee1fee66f8ea6a494d7d4ee7/demo/storybook/views.py#L13-L33

import json

from django.http import HttpResponse, HttpResponseForbidden
from django.template.loader import render_to_string

from pattern_library.utils import (
    get_pattern_context_var_name,
    mark_context_strings_safe,
)
from rest_framework.views import APIView


class RenderPatternView(APIView):
    http_method_names = ("post",)

    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body.decode("utf-8"))
        except json.decoder.JSONDecodeError:
            return HttpResponseForbidden()

        template_name = data["template_name"]
        config = data["config"]

        context = config.get("context", {})

        mark_context_strings_safe(context)
        context[get_pattern_context_var_name()] = True
        rendered_pattern = render_to_string(
            template_name, request=request, context=context
        )

        return HttpResponse(rendered_pattern)

This feels small enough and generic enough that it could be part of the django-pattern-library package directly, so the Storybook integration is only a JS dependency rather than both JS and Python.

Metadata

Metadata

Assignees

No one assigned

    Labels

    djangoRelated to Django templates capabilitiesenhancementNew feature or requeststorybookUsage of Storybook will affect this

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions