首页 > 解决方案 > 在 Django 包中添加对 Alpine.js 的支持

问题描述

我正在使用一个包,它添加了一个 SVG 模板标签来将我的 SVG 内联到我的 Django 模板中。我分叉了该项目并添加了对将 HTML 属性传递给 SVG 的支持。所以,现在我可以像下面这样使用它:

    {% load svg %}

    <a class="font-semibold text-gray-850 href="#0">
       {% svg 'icon-chevron-down' class="inline -mb-0.5 w-4 h-4 ml-0.5 transition-transform duration-200 transform fill-current text-gray-400" %}
    </a>

但是当我想在 svg 中使用 Alpine.js 时遇到了问题。我希望能够做这样的事情:

{% svg 'icon-chevron-down' :class="{'rotate-180': open, 'rotate-0': !open}" class="inline -mb-0.5 w-4 h-4 ml-0.5 transition-transform duration-200 transform fill-current text-gray-400" %}

我怎样才能让它工作?

我的包裹的回购: https ://github.com/xshapira/django-simple-svg

svg.py

from __future__ import absolute_import
import logging
import os

from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.core.exceptions import ImproperlyConfigured
from django.utils.safestring import mark_safe

from simple_svg.exceptions import SVGNotFound

logger = logging.getLogger(__name__)
register = template.Library()


@register.simple_tag
def svg(filename, *args, **kwargs):
    SVG_DIRS = getattr(settings, "SVG_DIRS", [])

    if type(SVG_DIRS) != list:
        raise ImproperlyConfigured("SVG_DIRS setting must be a list")

    path = None

    if SVG_DIRS:
        for directory in SVG_DIRS:
            svg_path = os.path.join(
                directory, "{filename}.svg".format(filename=filename)
            )

            if os.path.isfile(svg_path):
                path = svg_path
    else:
        path = finders.find(
            os.path.join("svg", "{filename}.svg".format(filename=filename)), all=True
        )

    if not path:
        message = "SVG '{filename}.svg' not found".format(filename=filename)

        # Raise exception if DEBUG is True, else just log a warning.
        if settings.DEBUG:
            raise SVGNotFound(message)
        else:
            logger.warning(message)
            return ""

    # Sometimes path can be a list/tuple if there's more than one file found
    if isinstance(path, (list, tuple)):
        path = path[0]

    with open(path) as svg_file:
        svg = svg_file.read()

    if kwargs:
        attributes = " ".join(['{}="{}"'.format(k, v) for k, v in kwargs.items()])
        svg = svg.replace("<svg", "<svg " + attributes)

    svg = mark_safe(svg)

    return svg

测试.py

import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template import Context, Template
from django.test.testcases import SimpleTestCase

from simple_svg.exceptions import SVGNotFound


def test_should_support_attributes(self):
        svg_file = open(
            os.path.join(settings.BASE_DIR, "static", "svg", "django.svg")
        ).read()
        template = Template("{% load svg %}{% svg 'django' id='logo' class='large' %}")

        self.assertNotEqual(svg_file, template.render(Context()))
        self.assertIn('id="logo"', template.render(Context()))
        self.assertIn('class="large"', template.render(Context()))

标签: python-3.xdjangosvgdjango-templatesalpine.js

解决方案


一个简单的解决方案

我找到了一种更好的方法,无需更改 Django 包中的任何内容。我们可以简单地svg用 a 包装标签div并将类和 Alpine.js 表达式应用于它。这是一个例子:

<div :class="{'rotate-180': open, 'rotate-0': !open}" class="inline -mb-0.5 w-4 h-4 ml-0.5 transition-transform duration-200 transform fill-current text-gray-400">
  {% svg 'icon-chevron-down' %}
</div>

推荐阅读