venveo/craft-compress

动态创建Craft资产的智能压缩包

5.0.0 2024-09-24 20:32 UTC

README

Compress在Twig中暴露一个变量,可以从资产查询中创建zip存档,作为本地的Craft资产本身。

功能

  • 将资产查询压缩成zip文件
  • 生成“懒加载链接”:如果用户在任务完成或开始之前点击链接,将调度队列任务以生成存档。如果资产在需要时获取,则取消队列任务。
  • 压缩存档作为资产本身存储,因此您可以像查询其他资产一样查询它们。
  • 检索存档内容的资产查询,以显示其中包含的文件。
  • 当Craft中的依赖资产被删除或更新时,自动强制重新生成zip文件。

要求

  • Craft CMS 3.x-5.x
  • 用于创建zip文件的ext-zip PHP扩展(也是Craft的要求之一)

安装

要安装插件,请按照以下说明操作。

  1. 打开您的终端并转到您的Craft项目

     cd /path/to/project
    
  2. 然后告诉Composer加载插件

     composer require venveo/craft-compress
    
  3. 在控制面板中,转到设置→插件,然后点击Compress的“安装”按钮。

配置Compress

  1. Compress在Craft中将其存档作为资产创建,因此您需要一个地方来放置它们。创建一个新的卷。
  2. 在插件列表中点击插件旁边的“设置”,并选择存档的存储卷。不建议使用现有的卷。卷必须有URL,以便Twig辅助函数返回下载链接;然而,它将正常工作并尊重您的设置和选择。

使用Compress

基本示例

    {# Feel free to provide an array of assets if you prefer! #}
    {% set assets = craft.assets.volume('images') %}
    
    {# 
    Second parameter is whether we want the archive generated on page 
    load or lazily.
    #}
    {% set archive = craft.compress.zip(assets, true, 'My Photos') %}
    
    {# 
    the archive variable is now set to an Archive model, but since 
    we're in lazy mode, the getAsset() response may be null. We can
    either check the .isReady method or we can just get the lazyLink, which will give us an indirect link to the asset.
    #}
    {% if archive.isReady %}
        {% set archiveAsset = archive.getAsset() %}
        <a href="{{ archiveAsset.getUrl() }}">Download All Files</a>
        {% else %}
        <a href="{{ archive.lazyLink}}">Download All Files</a>
    {% endif %}
    
    {# We can get a new AssetQuery with the contents of the archive! #}
    {% set contents = archiveAsset.getContents().all() %}
    <ul>
    {% for file in contents %}
        <li><a href="{{ file.getUrl() }}">{{ file.title }}</a></li>
    {% endfor %}
    </ul>

高级示例

此示例获取所有资产,按文件类型分组,然后生成一个懒加载链接以下载特定类型的所有资产。

{% set assets = craft.assets({
    volume: 'local'
}).all() %}

{% for kind, assetGroup in assets|group(a => a.kind) %}
    {% set archive = craft.compress.zip(assetGroup, true) %}
    <strong>{{ kind }} - <a href="{{ archive.lazyLink }}">Download All ({{ archive.isReady ? 'Ready' : 'Not ready' }})</a></strong>
    {% for asset in assetGroup %}
        <li>{{ asset.filename }}</li>
    {% endfor %}
{% endfor %}

注意事项与限制

  • 请将Compress创建的资产视为临时资产。不要尝试在资产关系字段中使用它们。更改设置,将创建一个新的存档资产,而先前的资产不会被自动删除。
  • 当您为存档提供名称时,请确保该名称对于您要压缩的文件是唯一的。如果没有这样做,可能会导致文件缓存不良并不断被覆盖。

Venveo提供