Codeistry

MODx Snippet: ChunkIf

Ages ago, I wrote a MODx snippet called ChunkIf and I thought it was about time that I shared it with the MODx community. ChunkIf allows you to choose which of two chunks gets output, based on a template variable being set or not; its not big or clever but I find it useful and hopefully you might do, too.

The long form of the snippet call looks like this:

[[ChunkIf? &tv=`tvname` &trueChunk=`chunkname` &falseChunk=`chunkname`  &debug=`1|0` ]]

The parameters to the snippet call work like this:

&tv
This is the name of the template variable you want to test. The value of this variable will be checked and if it’s not empty or blank, &trueChunk will be output – otherwise &falseChunk will be.
&trueChunk
The name of the chunk who’s content you want output, in the event that your template variable (&tv) has a value.
&falseChunk
The name of the chunk who’s content you want output, if your template variable (&tv) is empty. If you omit this parameter, an empty string will be output if &tv is empty.
&debug
Set this to 1 to emit debugging comments into the HTML output; set it to 0 or leave it out to switch off.

There is a short version too:

[[ChunkIf? &tv=`tvname` ]]

The shorthand form attempts to output the contents of a chunk with the same name as &tv, if &tv is set, or an empty string. If there’s no chunk with the same name, it also returns an empty string.

This shorthand version is very handy for switching chunks on and off using a single variable. As chunks can contain other chunks and snippet calls, you can use this to switch sidebars, footers and other complex bits of layout on and off on a per page basis, with a simple checkbox template variable.


<?php
	/*
		Version: 0.2
		Date: 21/07/2008
		Description:
			<strong>0.2</strong> Outputs the contents of the chunk passed in
			$trueChunk if the template variable passed in $tv is set (i.e. has a value).
			Otherwise outputs the contents of the $falseChunk chunk. Expects $tv to be the
			name of the Template Variable to test, and $trueChunk & $falseChunk to be names
			of chunks.

		eg:

		[[ChunkIf? &tv=`tvname` &trueChunk=`chunkname` &falseChunk=`chunkname` ]]
			- Long version outputs $trueChunk if $tv has a value, otherwise
			outputs $falseChunk.
		[[ChunkIf? &tv=`tvname` &trueChunk=`chunkname` ]]
			- This short version outputs an empty string if $tv has no value.
		[[ChunkIf? &tv=`tvname` ]]
			- This very short version attempts to output the contents of a chunk
			 with the same name as $tv
		[[ChunkIf? &tv=`tvname` &debug=`1` ]]
			- Switches on debugging output - output's HTML comments for debugging.

	*/

	// get tv name
	$tv = isset( $tv ) ? $tv : '';

	// get current page ID
	$id = isset( $id )? $id: $modx -> documentObject['id'];

	// Get the value of $tv
	$tvarray = $modx -> getTemplateVarOutput( $tv, $id );
	$value = ''.trim($tvarray[$tv]);

	if ($debug) {
		$dtmp = '<!--';
		$dtmp .= 'tv: '.$tv.', ';
		$dtmp .=  'id: '.$id.', ';
		$dtmp .=  'value: '.$value;
		$dtmp .=  '-->';

		echo $dtmp;
	}

	// Decide which chunk to return.
	if ($value == '') {
		// get chunk to return if $tv has no value
		$falseChunk = isset( $falseChunk )? $modx -> getChunk( $falseChunk ): '';
		return $falseChunk;
	} else {
		// get chunk to return if $tv has a value
		if (isset( $trueChunk ))
		{
			$trueChunk = $modx -> getChunk( $trueChunk );
		} else {
			// Attempt to get the chunk with the same name as $tv
			$trueChunk = $modx -> getChunk( $tv );
		}
		return $trueChunk;
	}
?>

Tags: ,

 

10 Responses to “MODx Snippet: ChunkIf”

  1. [...] in the community and that we can all help improve. I’ve started this process already with the ChunkIf snippet (below) – but there’s lots more where that came [...]

  2. A says:

    Thanks, this snippet is very helpful for me. I was trying to do something similar but couldn’t quite figure it out.

  3. Jorgen says:

    Hi,

    Seems like a very usefull snippet, but can’t seem to get it going. I get an error on line 27, unexpected T_VARIABLE, which means de variable TV doesn’t exist?
    Hope you can help me out.

  4. Jorgen says:

    Nevermind. I found that your code in the box above is rendered in HTML entities. So the -> is replaced with the HTML code. Which of course doesn’t get parsed very well.

  5. Duncan Lock says:

    Thanks for pointing that out Jorgen, it got mangled by the syntax highlighter, I think. I’ve fixed it and changed the highlighter that I’m using.

    Cheers,
    Dunc

  6. Raf sixty-huit says:

    Thanks for that snippet.

    It works at first try ;)

  7. Lester says:

    Hi, thanks for this simple but useful snippet.
    Related with that I have a question. What about if one of the chunks must contains an snippet call? I did try it an uncached ([!snippetName!]) call but MODx output the snippet call literally, without parsing it. The only way is calling the snippet in cached way ([[snippetName]]), but that isn’t fine for all kind of snippets. Do you have a solution for that?

    Regards,
    Lester

  8. Duncan Lock says:

    You might like to read through this MODx wiki article which covers this in detail:

    http://wiki.modxcms.com/index.php/Snippet_call_anatomy

    If this doesn’t answer your question fully, then you might like to try running your site completely un-cached. I sometimes do this for smaller sites with less traffic. The affect on visitors is minimal or non-existent, it smooths out the editing experience for editors and eliminates issues like this. You can change the cache status of all pages on your site via the DocManager module, and set the default in the Configuration tab.

  9. lsd says:

    Is it possible to use this snippet in eForm tpl with select option to get chunk?

    Thanks

  10. Duncan Lock says:

    As in, you have a drop-down menu on the form and choosing different entries from the drop-down menu, causes different chunks to be displayed?
    Unless you’re going to submit the form, or do something clever with AJAX, no.
    This snippet – like all MODx snippets – is evaluated by the MODx Document Parser on the server, as the page is being built, before it’s sent back to the browser. Once the web page has been sent to the browser, it’s out of MODx’s hands, until another request is made to the server – i.e. a page refresh, new page request or a form submission.
    If you want to do things on the page after it’s been sent to the browser – without a page refresh – then you need javascript. Javascript – unlike PHP – is a client-side language and runs in the browser, so you can use it to do dynamic things on the page after it’s been sent to the browser. You could certainly show and hide bits of a form, based on selections in a drop-down, using javascript, if that’s what you wanted to do.

Leave a Reply

Codeistry blog is proudly powered by WordPress Entries (RSS) and Comments (RSS).