shorten smarty if statements
Asked Answered
P

2

1

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.

Pilau answered 5/7, 2012 at 1:17 Comment(0)
P
2

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}>
Pilau answered 5/7, 2012 at 1:17 Comment(0)
S
0

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}
Support answered 5/7, 2012 at 1:23 Comment(4)
thanks a lot for trying to help. But this doesn't answer my question and could have been a comment.Pilau
But you wanted to shorten the checks right? You may assign once the "pages" and "actions" and then only use shorten "if" statementSupport
I didnt see you edit. I will try and let you know how it goes. Cheers.Pilau
thanks a lot. But that doesnt work for me as I can write {php} in my code as I mentioned in the question.Pilau

© 2022 - 2024 — McMap. All rights reserved.