【问题标题】:How to create file download link in drupal 8如何在 drupal 8 中创建文件下载链接
【发布时间】:2015-09-08 11:00:40
【问题描述】:

我为 mp3 文件创建了一个自定义字段格式化程序,并添加了一个名为“提供下载链接”的设置表单字段,这是一个复选框。如果选中“提供下载链接”,我想提供文件下载链接。谁能告诉我如何在 drupal 8 中创建这个下载链接?我必须将动态下载链接传递给格式化程序模板文件(twig),以便用户可以通过单击链接下载 mp3 文件。

【问题讨论】:

    标签: drupal-8


    【解决方案1】:

    我假设您添加格式化程序的字段是允许上传文件的字段,例如 mp3 文件

    Mp3Formatter.php 假设这是格式化程序的类名。确保您的格式化程序类从 FileFormatterBase 扩展

        use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;
    
            // Get "Provide Download Link”  settings value.
            // Assuming the machine name you gave  to your setting is : download_link_setting.
            // Add the code below to your formatter class under the method body: viewElements
            // Get the referenced entities in this case files.
    
            $files = $this->getEntitiesToView($items);
    
            // initialise $url variable.
    
            $url = NULL;
    
            $download_link_setting = $this->getSetting(‘download_link_setting’);
    
            // Loop through the file entities.
    
            foreach ($files as $delta => $file) {
    
              // For each file add code below.
              // Check if the setting isn’t empty and then create the file url.
    
              if (!empty($download_link_setting)) {
                $mp3_uri = $file->getFileUri();
                $url = Url::fromUri(file_create_url($mp3_uri));
              }
    
              // Add the $url parameter to your render array e.g
    
              $elements[$delta] = [
                '#theme' => ‘mp3_formatter',
                '#item' => $item,
                '#url' => $url,
                '#filename' => $item->getFilename(),
              ];
            }
    
          return $elements;
    

    在模块的 .module 文件中。

            // Register your theme under hook_theme.
    
            'mp3_formatter' => [
              'variables' => [
                'item' => NULL, 
                'url' => NULL, 
                'filename' => NULL,
              ],
            ],
    

    在对应的 TWIG 模板中

            // Now add your download link into the twig element.
            // check if the url variable is set
            {% if url %}
              <a href="{{ url }}" download>{{ filename }}</a>
            {% else %}
              <p> {{ filename }} </p>
            {% endif %}
    

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 2018-04-29
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 2012-03-01
      相关资源
      最近更新 更多