Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for rendering patterns over an API endpoint #104

Closed
thibaudcolas opened this issue Feb 28, 2020 · 0 comments · Fixed by #168
Closed

Add support for rendering patterns over an API endpoint #104

thibaudcolas opened this issue Feb 28, 2020 · 0 comments · Fixed by #168
Labels
django Related to Django templates capabilities enhancement New feature or request storybook Usage of Storybook will affect this
Milestone

Comments

@thibaudcolas
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
django Related to Django templates capabilities enhancement New feature or request storybook Usage of Storybook will affect this
Projects
No open projects
Development

Successfully merging a pull request may close this issue.

1 participant