【问题标题】:Get length of string in TYPO3 Fluid template获取 TYPO3 Fluid 模板中的字符串长度
【发布时间】:2020-07-08 01:57:25
【问题描述】:

如何检查字符串的长度? 如果少于 8 个字符,我想添加一个类。

比如:

{f:if(condition: '{page.title -> f:count()} < 8', then: ' large')}

【问题讨论】:

  • 未经测试,但此条件应匹配:{f:if(condition: '{page.title} != {page.title -&gt; f:format.crop(maxCharacters: 8)}', then: ' large')}
  • f:format.crop 示例仅在 page.title 变量始终为 8 个或更多字符时才能正常工作;对于较短的字符串值将失败(误报)。
  • @JulianHofmann 非常聪明。效果很好,除了它应该是 == 用于小于匹配。您应该将此添加为答案。
  • @ClausDue,我忘了清空append,否则,我无法确认您的担忧。

标签: typo3 fluid typo3-9.x


【解决方案1】:

Fluid 可以通过一个小技巧来实现:

您将字符串裁剪到其最大长度并将结果与​​原始字符串进行比较。如果裁剪后的字符串与原始字符串匹配,则原始字符串比预期的要长。

{f:if(condition: '{page.title} != {page.title -> f:format.crop(maxCharacters: 8, append:\'\')}', then: ' large')}

注意:append 必须设置为空字符串。

示例

lib.stringLength = FLUIDTEMPLATE
lib.stringLength {
    variables {
        shortText = TEXT
        shortText.value = abc
        exactText = TEXT
        exactText.value = four
        longText = TEXT
        longText.value = Lorem ipsum
    }
    template = TEXT
    template.value(
        <h2>{shortText}</h2>
        <p>condition: '{shortText} != {shortText -> f:format.crop(maxCharacters: 4, append:'')}': <br />
            result: {f:if(condition: '{shortText} != {shortText -> f:format.crop(maxCharacters: 4, append:\'\')}', then: ' large')}
        </p>
        <hr />
        <h2>{exactText}</h2>
        <p>condition: '{exactText} != {exactText -> f:format.crop(maxCharacters: 4, append:'')}': <br />
            result: {f:if(condition: '{exactText} != {exactText -> f:format.crop(maxCharacters: 4, append:\'\')}', then: ' large')}
        </p>
        <hr />
        <h2>{longText}</h2>
        <p>condition: '{longText} != {longText -> f:format.crop(maxCharacters: 4, append:'')}': <br />
            result: {f:if(condition: '{longText} != {longText -> f:format.crop(maxCharacters: 4, append:\'\')}', then: ' large')}
        </p>
        <hr />
    )
}

结果:

abc

条件:'abc != abc':

结果:

四个

条件:'四个!=四个':

结果:

Lorem ipsum

条件:'Lorem ipsum != Lore':

结果:大

【讨论】:

    【解决方案2】:

    您可以尝试使用 vhs 包中的 v:count.bytes https://fluidtypo3.org/viewhelpers/vhs/master/Count/BytesViewHelper.html

    【讨论】:

    • 我希望找到一种无需额外扩展的方法
    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多