【问题标题】:How to put an object into template via Jinja2 in Django app using Coffin如何使用 Coffin 在 Django 应用程序中通过 Jinja2 将对象放入模板
【发布时间】:2012-01-06 10:26:35
【问题描述】:

我使用 CoffinJinja2Django 应用程序集成。我想在我的 Jinja2 模板中使用 sorl 应用程序。所以我决定为标签 {% thumbnail %} 编写我自己的扩展。我决定使用一个很棒的 WithExtension 作为例子,它来自一个带有棺材的盒子。

我的扩展:

class ThumbnailExtension(Extension):

tags = set(['thumbnail'])

def parse(self, parser):
    lineno = parser.stream.next().lineno
    value = parser.parse_expression()

    im = get_thumbnail(value.value, "100x100")

    parser.stream.expect('name:as')
    name = parser.stream.expect('name')
    body = parser.parse_statements(['name:endthumbnail'], drop_needle=True)
    # Use a local variable instead of a macro argument to alias
    # the expression.  This allows us to nest "with" statements.

    body.insert(0, nodes.Assign(nodes.Name(name.value, 'store'), im))

    return nodes.CallBlock(
            self.call_method('_render_block'), [], [], body).\
                set_lineno(lineno)

    def _render_block(self, caller=None):
        return caller()

我的模板:

{% thumbnail "jinja.png" as img %}
    {{ img.url }}
{% endthumbnail %}

但我收到了AttributeError: 'ImageFile' object has no attribute 'iter_child_nodes'

看来我应该将 jinja2.nodes.Node 对象作为第二个参数传递给 nodes.Assign()。我该怎么做?

【问题讨论】:

    标签: django tags thumbnails jinja2


    【解决方案1】:

    通过将 get_thumbnail 函数发送到模板中解决了问题:

    from sorl.thumbnail.shortcuts import get_thumbnail
    from coffin.template import Library
    register = Library()
    
    @register.object()
    def thumbnail(file_, geometry_string, **options):
        try:
            im = get_thumbnail(file_, geometry_string, **options)
        except IOError:
            im = None
        return im
    

    现在我可以直接从模板中调用它了:

    {% set image = thumbnail(image_object, params.size|default("100x100")) %}
    

    自定义标签或过滤器中没有必要。

    【讨论】:

    • 谢谢,这完美!我认为您只是在模板标签文件中缺少“来自 sorl.thumbnail.shortcuts import get_thumbnail”。
    【解决方案2】:

    这里有点类似,适合2016年使用,使用棺材的继任者django-jinja --

    from sorl.thumbnail.shortcuts import get_thumbnail
    from django_jinja import library
    
    @library.filter
    def thumbnail(path, geometry, **options):
        return get_thumbnail(path, geometry, **options)
    

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 2014-07-30
      • 2011-09-17
      • 2012-06-12
      • 2015-06-15
      • 2011-02-28
      • 2012-02-03
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多