How to place an object in a template via Jinja2 in a Django application using Coffin

I am using Coffin to integrate Jinja2 with a Django application. I want to use the sorl application in my Jinja2 template. So I decided to write my own extension for the {% thumbnail%} tag. I decided to use the excellent WithExtension as an example that goes out of the box with Coffin.

My extension:

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() 

My template:

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

But I get AttributeError: 'ImageFile' object has no attribute 'iter_child_nodes'

It seems that I should pass the jinja2.nodes.Node object as the second parameter to node.ssss (). How can I do it?

+4
source share
2 answers

The problem was solved by sending the get_thumbnail function to the template:

 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 

And now I can call it directly from the template:

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

There is no need for a custom tag or filter.

+4
source

Here's something similar, suitable for use in 2016, using the heir to the coffin, 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) 
+2
source

Source: https://habr.com/ru/post/1383081/


All Articles