I am trying to cut a slice a list of images to split them over a few pages of a pdf I am generating. But im not sure what the syntax I need to use is. (or if there is a better way).
{% for page in image_pages %} // range loop for number of pages (passed from view)
<p style="page-break-before: always"></p> // new page break for each page
<div >
{% for image in project_images|slice:"0:12" %}
<div style="margin: 5px">
<img
src="{{ base_url }}{{ image.path.url }}"
/>
</div>
{% endfor %}
</div>
{% endfor %}
What i want to do is adjust this line
{% for image in project_images|slice:"0:12" %}
To something like (to print 12 images from total image list sent)
{% for image in project_images|slice:"page*12:page*12 12" %}
CodePudding user response:
You could write your own template tag to slice with variable arguments. The Django-supplied template engine doesn't include this. The authors believe that the right place to do this sort of thing is in the Python code. Something like
display = []
for page in image_pages:
display.append([
page,
project_images[page*12:page*12 12]
])
context['display'] = display
And the template then becomes
{% for page, image_list in display %}
<p style="page-break-before: always"></p> // new page break for each page
<div >
{% for image in image_list %}
<div style="margin: 5px">
<img
src="{{ base_url }}{{ image.path.url }}"
/>
</div>
{% endfor %}
</div>
{% endfor %}
The other option is to use Jinja instead of the Django template engine.
CodePudding user response:
Along with this answer i did the below to achieve what i needed. https://stackoverflow.com/a/23783666/14143473. I also used https://pypi.org/project/django-mathfilters/
{% for page in image_pages %}
<p style="page-break-before: always"></p>
{% with start=page|mul:12 end=page|mul:12|add:12 %}
{% with start|addstr:":"|addstr:end as imageSlice %}
<div >
{% for image in project_images|slice:imageSlice %}
<div style="margin: 5px">
<img
src="{{ base_url }}{{ image.path.url }}"
/>
</div>
{% endfor %}
</div>
{% endwith %}
{% endwith %}
{% endfor %}