shorten smarty if statements

女生的网名这么多〃 提交于 2019-12-13 01:15:54

问题


I have a smarty if statement as follows:

<{if $page->getURLName() eq 'big-issues' or $page->getURLName() eq 'polls' or $page->getURLName() eq 'what-we-do' or $action eq 'events' or $action eq 'blogs' or $action eq 'news'}>

I have to compare the same statements several time in the template. And its really tedious to ugly to repeat this statements several times. I know I can cache a statements and reuse it many times but I was looking if its possible to do something like this:

<{if $page->getURLName() eq 'big-issues' or 'polls' or 'what-we-do' or 'events' or $action eq 'blogs' or 'news'}>

like in PHP we could do:

$url = array ("big-issues","polls","what-we-do");
$needle = $page->getURLName();
if(in_array($needle, $centered)) {
    //Do something
}

Please note that I dont have access to php code for the template so can only use smarty. Any suggestion will be highly appreciated.

Cheers.


回答1:


Actually this is the solution I came up with.

NOTE: In my template I have to use <{}> instead of {} to start smarty. Its just how the template is set up.

        <{$urlName = ['big-issues','polls','what-we-do']}>
        <{$actionType = ['news','blogs','events']}>

        <{foreach item="url" from=$urlName}>
            <{if $page->getURLName() eq $url}>
                <{assign var=showBlock value=1}>
            <{/if}>
        <{/foreach}>

        <{foreach item="act" from=$actionType}>
            <{if $action eq $act}>
                <{assign var=showBlock value=1}>
            <{/if}>
        <{/foreach}>

Now I could check many times in my HTML the same statements without messing up the code.

<{if $showblock}>
    <div class="block">
<{else}>
    <{div class="regular"}>
<{/if}>



回答2:


Check this: http://www.smarty.net/forums/viewtopic.php?p=48466

And this for assign to array within templates: How to assign an array within a smarty template file?

Should be something like this:

{assign var='pages' value=','|explode:"big-issues,polls,what-we-do,events"}
{assign var='actions' value=','|explode:"blogs,news"}

{if in_array($page->getURLName(), $pages) or in_array($action, $actions)}
do something
{/if}


来源:https://stackoverflow.com/questions/11336840/shorten-smarty-if-statements

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