Using regex replace with smarty template system?

痴心易碎 提交于 2019-12-24 03:33:03

问题


Here's what I currently have in my Smarty template:

<div class="tbl_pagination">
    {if $pager}{$pager->links}{/if}
<div>

My {$pager->links} will output this HTML:

<div class="tbl_pagination">
    <ul><li><a href="javascript:toPage(3)" title="previous page">Back</a></li>
    <li><a href="javascript:toPage(1)" title="page 1">1</a></li>
    <li><a href="javascript:toPage(2)" title="page 2">2</a></li>
    <li><a href="javascript:toPage(3)" title="page 3">3</a></li>
    <li class='active'>4</li>
    <li><a href="javascript:toPage(5)" title="page 5">5</a></li>
    <li><a href="javascript:toPage(6)" title="page 6">6</a></li>
    <li><a href="javascript:toPage(7)" title="page 7">7</a></li>
    <li><a href="javascript:toPage(5)" title="next page">Next</a></li>
    </ul></div>
</div>

I'm trying to replace two different things:

  1. I want to completed remove the title attribute.

  2. Whichever li has the class active needs to also have an a href.

Here's what I'd like it to look like:

<div class="tbl_pagination">
    <ul><li><a href="javascript:toPage(3)">Back</a></li>
    <li><a href="javascript:toPage(1)">1</a></li>
    <li><a href="javascript:toPage(2)">2</a></li>
    <li><a href="javascript:toPage(3)">3</a></li>
    <li class='active'><a href="#">4</a></li>
    <li><a href="javascript:toPage(5)">5</a></li>
    <li><a href="javascript:toPage(6)">6</a></li>
    <li><a href="javascript:toPage(7)">7</a></li>
    <li><a href="javascript:toPage(5)">Next</a></li>
    </ul></div>
</div>

Is this possible to do in the Smarty template system using their replace function?


回答1:


Since you mentioned in your comments that you achieved (2) on your own, here's a solution for the first replace, with 2 methods:

  1. You can use regex_replace:

    {$pager->links|regex_replace:'/title="[\w\s]+"/':""}

  2. Alternatively, you can use directly php's preg_replace, like this:

    {'/title="[\w\s]+"/'|preg_replace:'':$pager->links}

This might seem weird at first, but let me explain the syntax:

Smarty supports passing a variable/string to some php function using the | (pipe) symbol. However, additional parameters are then passed with the : (colon) parameter. This is consistent for the syntax of Variable Modifiers

For example, if you wanted to count the letters on your string, you would do:

{$pager->links|strlen}

And if you wanted to see if a value foo is within an array $bar you would do:

{'foo'|in_array:$bar}

so, for a php function that looks like func($arg1, $arg2, $arg3), this translates to {$arg1|func:$arg2:$arg3}

Needless to say the preferred method is (1), I only suggested the 2nd because, to my opinion, it is interesting to know.



来源:https://stackoverflow.com/questions/26565225/using-regex-replace-with-smarty-template-system

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!