We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 3125
    • 8 Posts
    Hi,

    I’m trying to get my brain into the modx gear and finding it a bit hard as I am used to working with the smarty template system, so I hope someone can help me with the following question.

    I basically just want to include some javascript files for specific pages (using the same template). In a smarty template I would do something like this
    {if $page_id == 4}
    <script type="javascript/text" src="js/blah.js"></script>
    {/if}

    I’m just wondering how I would achieve this in modx without making a new template? Would I have to write a snippet or use a TV? Which method would be best?

    Thanks.
      • 26931
      • 2,314 Posts
        • 16278
        • 928 Posts
        Unless you’re already using PHx elsewhere on the site, you might find a purpose-built snippet easier to implement and maintain.

        In the template:
        <script type="javascript/text" src="js/[!setScript?script=`[*id*]`!]"></script>

        The snippet:
        <?php
        // setScript
        // input: &script, page id
        
        switch($script) {
        	case '1':
        	 $js = 'one.js';
        	 break;
        	case '2':
        	 $js = 'two.js';
        	 break;
        	default:
        	 $js = 'general.js';
        	}
        return $js;
        ?>

        I also find using page aliases and [*alias*] rather than numerical IDs for the parameter and the switch criteria is less error-prone. Ir also avoids problems with string|number comparisons that can sometimes arise in PHP.

        I’ve not tested the specific code above, but I’ve used similar stuff for context-sensitive menus with no problems.
        smiley KP