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

Drupal模板中如何在Twig变量里替换字符串的第N次出现?

Drupal Paragraphs 指定位置</p>标签替换实现方案

方案1:使用预处理钩子(推荐,性能最优)

在你的主题.theme文件或者自定义模块文件中添加对应Paragraph bundle的预处理钩子,直接修改字段渲染内容:

// 把YOUR_THEME改为你的主题机器名,YOUR_BUNDLE改为目标Paragraph的bundle机器名
function YOUR_THEME_preprocess_paragraph__YOUR_BUNDLE(&$variables) {
  // 替换为你要处理的文本字段机器名,示例为field_body
  if (empty($variables['content']['field_body'][0]['#text'])) {
    return;
  }

  $original_html = $variables['content']['field_body'][0]['#text'];
  // 自定义要插入的内容
  $insert_content = '</p><div>你要插入的自定义内容</div>';
  // 填写需要替换的第N次出现的位置,示例为第2、3次
  $target_replacements = [2, 3];
  $match_count = 0;

  // 用正则回调实现指定位置替换
  $modified_html = preg_replace_callback(
    '#</p>#i',
    function ($matches) use (&$match_count, $target_replacements, $insert_content) {
      $match_count++;
      return in_array($match_count, $target_replacements) ? $insert_content : $matches[0];
    },
    $original_html
  );

  // 把修改后的内容写回渲染数组
  $variables['content']['field_body'][0]['#text'] = $modified_html;
}

修改完成后清空Drupal缓存即可生效。

方案2:Twig模板层处理

如果需要在模板中灵活控制替换逻辑,可以先自定义一个replace_nth Twig过滤器,之后在paragraph--YOUR_BUNDLE.html.twig模板中直接调用:

{# 示例:替换第2、3次出现的</p>标签 #}
{{ content.field_body|render|replace_nth('</p>', [2,3], '</p><div>自定义内容</div>') }}

注意事项

  • 不要直接对整体{{ content }}做替换,建议单独抽离目标文本字段处理,避免破坏Paragraphs其他组件的渲染结构
  • 如果开启了字段缓存,修改后需要清空对应缓存,或者给渲染数组添加对应缓存标签保证动态更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:24:07