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

模板变量处理需求:为指定{{ variable }}添加HTML标签且避免重复包裹

Solution for Wrapping Template Variables with Specific HTML Tag

Here's a practical, step-by-step approach to solve your problem of conditionally wrapping {{ }} template expressions with <b class="xyz">—let's break this down clearly:

Core Rules to Follow

  • Wrap a {{ ... }} block with <b class="xyz"> only if both conditions are met:
    • The content inside {{ }} includes the standalone term variable (not variants like variable1 where it's part of a longer identifier)
    • The {{ ... }} block isn't already enclosed in <b class="xyz"> tags
  • Never modify the inner content of the {{ }} block—just wrap it when eligible

Example Input & Output

Input Code

<ol>
 <li>&lt;P&gt; {{ variable | money_with_currency }} &lt;/P&gt; </li>
 <li>&lt;P&gt; {{variable1 | money }} something &lt;/P&gt; </li>
 <li>&lt;div&gt; {{ variable | filter}} &lt;/div&gt; </li>
 <li>&lt;P&gt;&lt;b class="xyz"&gt; {{ variable | filter }} &lt;/b&gt;&lt;/P&gt; </li>
</ol>

Output Code

<ol>
 <li><p>&lt;P&gt;&lt;b class="xyz"&gt; {{ variable | money_with_currency }} &lt;/b&gt;&lt;/P&gt;</p></li>
 <li><p>&lt;P&gt; {{ variable1 | money }} something &lt;/P&gt;</p></li>
 <li><p>&lt;div&gt;&lt;b class="xyz"&gt; {{ variable | filter }} &lt;/b&gt;&lt;/div&gt;</p></li>
 <li><p>&lt;P&gt;&lt;b class="xyz"&gt; {{ variable | filter }} &lt;/b&gt;&lt;/P&gt;</p></li>
</ol>

Case-by-Case Processing Logic

Let's walk through each line to clarify why the output looks the way it does:

  • Line 1: Wrapped — The {{ variable | money_with_currency }} has the exact standalone variable term and no existing <b class="xyz"> wrapper, so we add the tag.
  • Line 2: Unchanged — The expression uses variable1, which doesn't match our required variable term, so we leave it alone.
  • Line 3: Wrapped — The {{ variable | filter}} meets both conditions (has variable, no existing wrapper), so we apply the tag.
  • Line 4: Unchanged — The {{ variable | filter }} is already inside <b class="xyz">, so we don't duplicate the wrapper.

Regex-Based Implementation (For Tools/Scripts)

If you're using a regex-compatible tool or language, you can use this pattern to target eligible blocks:

Regex Pattern

(?<!<b class="xyz">)\{{2}\s*(variable\b.*?)\}{2}(?!<\/b>)

Replacement String

<b class="xyz"> {{ $1 }} </b>

Note: Ensure your regex engine supports lookbehind assertions. If not, first filter out blocks already wrapped in <b class="xyz">, then process the remaining ones.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:54:47