模板变量处理需求:为指定{{ 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 termvariable(not variants likevariable1where it's part of a longer identifier) - The
{{ ... }}block isn't already enclosed in<b class="xyz">tags
- The content inside
- Never modify the inner content of the
{{ }}block—just wrap it when eligible
Example Input & Output
Input Code
<ol> <li><P> {{ variable | money_with_currency }} </P> </li> <li><P> {{variable1 | money }} something </P> </li> <li><div> {{ variable | filter}} </div> </li> <li><P><b class="xyz"> {{ variable | filter }} </b></P> </li> </ol>
Output Code
<ol> <li><p><P><b class="xyz"> {{ variable | money_with_currency }} </b></P></p></li> <li><p><P> {{ variable1 | money }} something </P></p></li> <li><p><div><b class="xyz"> {{ variable | filter }} </b></div></p></li> <li><p><P><b class="xyz"> {{ variable | filter }} </b></P></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 standalonevariableterm and no existing<b class="xyz">wrapper, so we add the tag. - Line 2: Unchanged — The expression uses
variable1, which doesn't match our requiredvariableterm, so we leave it alone. - Line 3: Wrapped — The
{{ variable | filter}}meets both conditions (hasvariable, 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
相关产品推荐
相关产品推荐

