We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 8109
    • 128 Posts
    This is cross-posted, as I originally posted this to the Templates forum, where it got no traction.

    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;
           }
    ?>


    In my initial tests I discovered that you must call this snippet for every template in your sight, or else you will get multiple chunks inserted where you only wanted one.

    For instance, if you use htis chunk thusly:

    [[ifTemplate? &template=`article` &trueChunk=`articleContent` ]]
    [[ifTemplate? &template=`affiliateListings` &trueChunk=`affiliateContent` &falseChunk=`standardContent`]]

    and the current template is `article`, then you will get the `articleContent` chunk placed by the first call, and the falseChunk `standardContent` placed by the second call. This is not desired behavior. In other words, the false chunk feature doesn’t work. Instead, you’d need to have a separate call of ifTemplate for each Template, inserting `stadardContent` as the trueChunk for each to get this to work as it is.

    I realize now that the snippet should take a comma-delimited list of templates and their corresponding chunks, to be the most compact (as is the case for the extended version of the ifChunk snippit), but before continuing with this project, I’d like to know if there is a perceived need or desired in the ModX community for this snippet.
      Revo 2.0.8-pl
      • 28042 ☆ A M B ☆
      • 24,524 Posts
      Perhaps I’m missing something, but isn’t that exactly what Template Variables are for?
        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
        • 5689
        • 289 Posts
        Yeah, I don’t quite understand how to apply this, either. What do you mean by global template? Templates contain the code specific to that template, so how would we use this snippet to do the same thing?
          I&#39;m learning more about MODx all the time and loving it.
          • 8109
          • 128 Posts
          Susan, we’ve had this discussion before. You *can* use TVs to include chunks and other information in various ways, but if the point is to include a chunk based on the current document’s template, then introducing a TV is duplicating information already available in the assigned template (namely, what template is assigned to the current document). Moreover, this snippet is designed to be used in the template code.

          By global template, I meant that you can have a file/chunk/code or any sort that is the template (the html code) for your site. Your documents are assigned to templates (in the ModX sense), possibly because you want to use TVs and associate them with certain documents. OR, possibly because you want the layout of the web page to be different for those documents assigned to that ModX template name. Possibly both.

          What I’m proposing is using a global template code (code, not ModX template) to make maintenance of template code simpler. In other words, every page, regarless of its assigned template, will have the same template code (called as a chunk, for instance). Then, if document assigned to one named template require a sidebar, while others templates don’t, this snippet allows you to insert that sidebar code in the template (code) based on the current document’s template name.

          (As I have said before, not having different words to describe these two types of templates makes this cumbersome to describe.)

          On my site, I now use this snippet to include files in the header of each page that are required for my "store" pages (those pages assigned to the template "store"), since all store pages require certain css and javscript files to be included to function, but I don’t want to load those into other documents where they are not needed. I use this snippet to include the chunk used to display the TVs and their associated html for all documents assigned to the template "story", and so on. One section of the site will need a third sidebar for a menu, and since this is the case of all documents assigned to the template called "affiliates" this snippet allows me to add this into my "global template" code so that I can maintain ONE file for the site’s html "template", instead of 5 or 6, one for each ModX template.

          The snippet says, for instance: Is the current ducument assigned to the template named "store"? If so, include the chunk called "store_javascript_includes".

          Is the current document assigned to the template named "affiliates"? If so, include the chunk called "affiliate_sidebar".

          Of course, I could set up a TV (or more than one) to do the same thing, and have those TVs clutter up the editor page of every document in the site, potentially confusing content editors. Or I can use this snippet in the template code.

          Perhaps I’m overlooking a totally simple way to do this.

          IN SUMMARY: This snippet allows you to maintain one template html file while changing the code included in the output based on the current document’s template name. It eliminates the need for superfluous Template Variables by using the implicit TV provided by the template’s name.
            Revo 2.0.8-pl
            • 5689
            • 289 Posts
            Thanks for the explanation. I understand a lot better now what you mean. I can definitely see how this would be useful. The only question I have now is, for the code of each MODx template, how do you load the code from a chunk or file? What would be a specific example of the code I would put in all of my MODx templates to load the global template?

            Thanks. laugh I might have to use this snippet.
              I&#39;m learning more about MODx all the time and loving it.
              • 7155
              • 160 Posts
              I’m still trying swear by MODx. so until i have etched TVs into my hard lil nut, I will be able to appreciate it better.

              I will imagine a scenario in which I would need it

              all the best though
                • 8109
                • 128 Posts
                All my templates now call the chunk called "globalTemplate".

                "globalTemplate" uses the snippet "ifTemplate" to insert chunks specific to each Template.

                In this way, there is a single template code. No need to maintain separate template codes for each template.

                It’s all explained in my original post.

                That’s it!

                (but I’m beginning to see that ModX is a roll-your-own platform. I’ll develop this a little further in case anyone finds it useful)
                  Revo 2.0.8-pl
                  • 5340
                  • 1,624 Posts
                  I guess this is ok for simple and few templates. When you have 10 very different templates the logic might get too complicated.
                    • 3749
                    • 24,544 Posts

                    What I’m proposing is using a global template code (code, not ModX template) to make maintenance of template code simpler. In other words, every page, regarless of its assigned template, will have the same template code (called as a chunk, for instance). Then, if document assigned to one named template require a sidebar, while others templates don’t, this snippet allows you to insert that sidebar code in the template (code) based on the current document’s template name.

                    (As I have said before, not having different words to describe these two types of templates makes this cumbersome to describe.)

                    I’m afraid this is making me dizzy. If template code is in a chunk, it isn’t template code -- it’s chunk code. The only template code in MODx is in templates themselves and the only templates are the ones attached to documents in the "Uses Template" field on the Create/Edit Resource screen. Chunks are called chunks and the template-like chunks with placeholders that are used to format output (usually as snippet parameters) are called "Tpl Chunks" (although not all the documentation has caught up to this terminology).

                    You’re clearly describing multiple templates, but seem to be claiming that what you’re suggesting will let you have a single template. If your site had only one template, your snippet wouldn’t have much to do. wink

                    If one page requires a sidebar and another doesn’t, why not put the sidebar in one template and not in another? Or use sottwell’s suggestion and create a sidebar/no_sidebar TV with radio buttons and have it return a chunk name (one chunk with a sidebar and the other without a sidebar). If you put the code that goes in *all* templates into chunks, I think you accomplish the same thing a lot faster and easier and without a snippet.

                    Maybe I’m missing something.

                    You’re absolutely free to design your site any way you want but please try to use MODx terminology correctly because new users are confused enough already. wink
                      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
                      • 16183
                      • 1,390 Posts
                      Maybe we need to see this in a screencast or something. I have to admit I am not getting the hang of it either smiley

                      cheers/k

                      ps: we’re not bashing you at all....;)