We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 8109
    • 128 Posts
    I have written a new snippet that allows you to insert a chunk based on the current document’s assigned template .

    Suggested use: if you have multiple templates assigned to documents in your site, and these templates require different html, css, or other includes, you can use this snippet to maintain a single source code for the template’s html.

    For instance, if you have a section of your site assigned to the template "article", which includes TV’s for author and references, you may insert a chunk that includes those TVs (possibly using the "chunkIf" snippet, on which the current snippet’s code is based). Another template, for instance "affiliatedClubs," may require two divs, one for a sub-menu of club names or locations, another for each affiliate’s contact information. All other templates in use might be the same. The ifTemplate snippet has the option to call a chunk ("falseChunk") if the current template is not matched in order to handle all other cases.

    Your global template might look like this:

    <head>
    
    {{headerChunk}}
    
    </head>
    
    <body>
    
    [[ifTemplate? &template=`article` &trueChunk=`articleContent` ]]
    [[ifTemplate? &template=`affiliateListings` &trueChunk=`affiliateContent` &falseChunk=`standardContent`]]
    
    ...
    
    </body>
    


    As you can see, this handles three different sets of template codes in one template file and is suitable for use with all assigned templates in the site. In fact, the above could all be included in a single chunk that would be called in every template on the site.

    A short call for this snippet would look like this:

    [[ifTemplate? &template=`article` ]]


    and will return a chunk with the same name as the template (in this case "article"), if it exists. This probably isn’t useful, but was part of the ifChunk code, so I duplicated that here.

    Here is the snippet code. I welcome comments for its improvement. It is my first snippet!

    <?php
    /*
    		Name: ifTemplate
    		Author: Russell Wagner <[email protected]>
    		Version: 0.1
    		Date: 30 June 2009
                    Credits: This snippet is based on the snippet ChunkIf by Duncan Lock <[email protected]>.
    		Description:
    			<strong>0.1</strong> Outputs the contents of the chunk passed in
    			$trueChunk if the template name passed in $template is the name of the current 
                            document's template. Otherwise outputs the contents of the $falseChunk chunk. Expects $template 
                            to be a tempalte name and $trueChunk & $falseChunk to be names of chunks.
    
    		eg:
    		
    		[[ifTemplate? &template=`templateName` &trueChunk=`chunkName` &falseChunk=`chunkName` ]]
    			- Long version outputs $trueChunk if $template equals current template name, otherwise 
      			  outputs $falseChunk.
    		[[ifTemplate? &template=`templateName` &trueChunk=`chunkName` ]]
    			- This short version outputs an empty string if $template does not match current document template's name
    		[[ifTemplate? &template=`tvname` ]]
    			- This very short version attempts to output the contents of a chunk
    			 with the same name as $tempalte
    		[[ifTemplate? &template=`tvname` &debug=`1` ]]
    			- Switches on debugging output - outputs HTML comments for debugging.
    	*/
    
    	$template = isset( $template ) ? $template : '';
           
           $docTemplateName = $modx -> db -> getValue('SELECT templatename FROM '.$modx->getFullTableName('site_templates').' WHERE id='.$modx->documentObject['template']);
           $docTemplateName = ''.trim($docTemplateName);
    
    	if ($debug) {
                   $dtmp = '';
                   $dtmp = '<!--';
                   $dtmp .= '<p>Specified template: ' .$template;
                   $dtmp .=  '<p>docTemplateName: '.$docTemplateName;
                   $dtmp .= '<p>Specified trueChunk: ' .$trueChunk;
    	       $dtmp .=  '-->';
    	       echo $dtmp;
    	}
    
    	// Decide which chunk to return.
           //if template is not a match, then return falseChunk or nothing if falseChunk is not set
           //I'm doing this first, since I assume that the negative case is most common, and we want to cut down on overhead
    
    	if ($template != $docTemplateName)  {    
                   $falseChunk = isset( $falseChunk )? $modx -> getChunk( $falseChunk ): '';
    	       return $falseChunk;
           }
          else {
                   //return trueChunk if it's set, else try to return the chunk with the same name as the template
    		if (isset( $trueChunk )) {
    			$trueChunk = $modx -> getChunk( $trueChunk );
    		} 
                    else  {
    			//Attempt to get the chunk with the same name as $template
    			$trueChunk = $modx -> getChunk( $template );
    		}
    		return $trueChunk;
           }
    ?>
      Revo 2.0.8-pl
      • 3749
      • 24,544 Posts
      Thanks for the contribution. smiley

      I hope you don’t mind if I make a couple of minor suggestions.

      First, it’s ’snippet’ not ’snippit’ and if you spell it correctly people will have an easier time finding your add-on.

      Second, you mentioned in the other thread that it’s too bad that the word ’template’ has two different meanings. Actually, only the templates listed in the Manager under Templates and assigned to documents in the Manager are correctly called templates. The template-like chunks used to manage the output of snippets and other things are called ’tpl chunks’ (sometimes ’TPLs’ for short) although not everyone uses the correct term. If you call them that in the descriptions of your snippet, it will help avoid a lot of confusion for people who use your snippet. smiley
        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
        • 8109
        • 128 Posts
        Great, Thanks, I’ll make the needed changes.
          Revo 2.0.8-pl
          • 5689
          • 289 Posts
          I like the idea of this, but I’m not quite clear on how it’s meant to be used. When you say ’global template’, what do you mean? What would be some example code that would go in the ’article’ template?

          I like the idea of using one place for all my template code, so I’m definitely interested in this.
            I&#39;m learning more about MODx all the time and loving it.
            • 36776
            • 31 Posts
            tropicaljuice Reply #5, 14 years ago
            Anyone know if this is for Evolution or Revolution?

            After several hours searching, i finally found this thread, but when trying it out I get error messages in Revolution.
              • 28042 ☆ A M B ☆
              • 24,524 Posts
              This is for Evo. Revo doesn't have a db object.
                Studying MODX in the desert - http://sottwell.com
                Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                Join the Slack Community - http://modx.org
                • 36776
                • 31 Posts
                tropicaljuice Reply #7, 14 years ago
                Ok. Does anyone know about an alternative?

                I was looking at the If addon, but I cant found out how to do this:
                If template = Front page, show this chunk
                If template = Template1, show this chunk
                If template = Front page, dont show this chunk, else show it.

                If you understand.
                ________

                The reason is that i have some javascripts thats only needed on some templates. To make it easy adding new template, I'm setting the header and footer part in chunks, so I can easy add it to new templates.

                  • 28042 ☆ A M B ☆
                  • 24,524 Posts
                  I use snippets for those. The snippet can be added either to the template or the resource using the javascript. You could even use a TV with checkboxes or radio buttons to indicate whether or not to load them for each resource.

                  They look something like this:

                  <?php
                  $modx->regClientScript('assets/js/jquery.prettyPhoto.js');
                  $modx->regClientCSS('assets/js/style/prettyPhoto.css');
                  $js = '
                  <script type="text/javascript" charset="utf-8">
                    $(document).ready(function(){
                      $("a[rel^=\'prettyPhoto\']").prettyPhoto();
                    });
                  </script>';
                  $modx->regClientScript($js);
                  ?>

                  regClientScript inserts the javascript just before the closing body tags at the bottom of the page, regClientCSS and regClientStartupScript load just before the closing head tags. [ed. note: sottwell last edited this post 14 years ago.]
                    Studying MODX in the desert - http://sottwell.com
                    Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                    Join the Slack Community - http://modx.org
                    • 36776
                    • 31 Posts
                    tropicaljuice Reply #9, 14 years ago
                    Hi,
                    Thanks for fast reply.

                    As i understod in your example, i need to add one snippet per javascript, and then add the snippet to the correct template?
                    Isnt that the same as just adding it directly in the template?


                    My templates looks like this:

                    [[$1001-1 TemplateHeaderHTML]]
                    template specific contents
                    [[$1001-1 TemplateFooterHTML]]


                    This chunks are global for all my templates.
                    And at the bottom of TemplateFooterHTML, i now have (witch dont work as you confirmed and is what i need to change)
                    [[ifTemplate? &template=`1001-1 Forside` &trueChunk=`1001-1 - TemplateFooterJSForside` ]]
                    [[ifTemplate? &template=`1001-1 Hosting Boxes` &trueChunk=`1001-1 TemplateFooterJSHosting Boxes` ]]
                      • 28042 ☆ A M B ☆
                      • 24,524 Posts
                      You could use a single snippet with a switch for the various templates, it would be much more efficient (as well as actually working) than a bunch of complicated filters.
                        Studying MODX in the desert - http://sottwell.com
                        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                        Join the Slack Community - http://modx.org