cooltronicpl / Craft-document-helpers

Craft CMS 3 and 4, 5 plugin enabling PDF document generation from template Twig files, code blocks and URLs
Other
13 stars 6 forks source link

File Download in a loop #10

Closed iwe-hi closed 2 years ago

iwe-hi commented 2 years ago

Hey there

Is it possible to download multiple files in a for loop? Something like this:


{% for entry in projects %}

        {{ craft.documentHelper.pdf("template", "download",  title, entry, pdfOptions) }}

{% endfor %}

Thank you for your answer.

cooltronicpl commented 2 years ago

Browser may ask for permission about download multiple files to end user. Simple example for some static files:

<script>
{% set pdfOptions = {
        date: entry.dateUpdated|date('U')
    } %}
    var files = ["{{ alias('@web') }}/{{craft.documentHelper.pdf('_pdf/document.twig', 'file', 'pdf/' ~ entry.dateCreated|date("Y-m-d") ~ random(10) ~ '.pdf'  ,entry, pdfOptions)}}", "{{ alias('@web') }}/{{craft.documentHelper.pdf('_pdf/document.twig', 'file', 'pdf/' ~ entry.dateCreated|date("Y-m-d") ~ random(10) ~ '.pdf' , entry, pdfOptions)}}"];
    for (var i = files.length - 1; i >= 0; i--) {
        var a = document.createElement("a");
        a.target = "_blank";
        a.download = "download";
        a.href = files[i];
        a.click();
    };
</script>

Simple example with loop:

{% set pdfOptions = {
        date: entry.dateUpdated|date('U')
    } %}
<script>
    var files = [
     {% for item in craft.entries.section('xxx').orderBy('title asc').all() %}

        "{{alias('@web')}}/
        {{craft.documentHelper.pdf("_pdf/document.twig", "file",  'pdf/' ~ item.id ~ '.pdf', item, pdfOptions)}}"

        {% if loop.last %}{% else %}, {% endif %}
    {% endfor %}
        ];
    for (var i = files.length - 1; i >= 0; i--) {
        var a = document.createElement("a");
        a.target = "_blank";
        a.download = "download";
        a.href = files[i];
        a.click();
    };
</script>