You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal 9 Webform邮件Twig模板文件链接缺失域名问题求助

解决Drupal 9 Webform邮件中图片链接缺失域名的问题

方法1:在Twig模板中直接替换相对路径为绝对路径

无需修改其他文件,直接在邮件Twig模板里处理token生成的HTML内容,拼接站点域名:

{% set file_links_html = webform_token('[webform_submission:values:photos_upload_new]', webform_submission, [], options) %}
{% set site_base_url = url('<front>', {absolute: true})|trim('/') %}
{# 替换所有相对路径的href为带域名的绝对路径 #}
{{ file_links_html|replace({'href="/': 'href="' ~ site_base_url ~ '/'}) }}

该方法快速见效,仅作用于当前邮件模板,无需改动模块代码或其他模板文件。

方法2:遍历文件字段直接生成绝对URL链接

跳过webform_token,直接遍历上传的文件对象手动构建带绝对路径的链接,灵活性更高:

{% if webform_submission.values.photos_upload_new is not empty %}
  {% for file in webform_submission.values.photos_upload_new %}
    <span>
      <a href="{{ file.url({absolute: true}) }}">{{ file.filename }}</a>
    </span>{% if not loop.last %}, {% endif %}
  {% endfor %}
{% endif %}

这种方式完全可控,不依赖token生成的HTML结构,适合需要自定义链接样式的场景。

方法3:通过hook_preprocess_file_link全局修正邮件中的文件链接

如果需要所有Webform邮件中的文件链接自动带域名,可在自定义模块中实现预处理钩子,仅在邮件场景下修改URL为绝对路径:

/**
 * Implements hook_preprocess_file_link().
 */
function YOUR_MODULE_preprocess_file_link(&$variables) {
  // 判断当前是否处于邮件发送场景,且文件来自Webform提交
  $is_mail_context = \Drupal::service('email.manager')->isMail();
  $is_webform_file = isset($variables['file']->webform_submission);
  
  if ($is_mail_context && $is_webform_file) {
    // 将URL设置为绝对路径
    $variables['url']->setAbsolute(TRUE);
  }
}

注意替换YOUR_MODULE为你的自定义模块名称,该方法会全局作用于符合条件的邮件文件链接,无需逐个修改模板。


内容的提问来源于stack exchange,提问作者summerg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:35:21