![]() Watch our free video course to learn more about Craft CMS and Twig control flow to learn more about how to control how and when you output content in your Twig templates. Now we have a much cleaner and more maintainable way to iterate over Matrix blocks while reacting to the different block types. The first thing we have to do is iterate over each of the items in the materials array, and then on each of those items’ type, we can do with cases checking for the type and then outputting the markup or content specific to that type. So it may look okay right now but using switch is a cleaner approach.Īnd this is what our code would look like with switch (I’ve added a bit more detail to the output code): We could accomplish this like this: īut with many cases to go through, this could get difficult to manage. Of course, I could accomplish this with a series of if statements, but it’s a bit more elegant to use switch. There could, potentially, be other layout issues we’d want to incorporate. The video course will have a preview, and the ebook will have a download sample. In C, if a switch statement has more than 6 cases for a scalar comparison, it will be. And this is imho much nicer than the if/else if/else if approach. I want to present different options depending on the course type. Placing the switch in a separate method allows you to place return statements directly inside the switch statement (at least in c), eliminating the need for break statements either, making the code much easier to read. Two of them are video-based, and one is an ebook. Let’s say we have a data set for a few online courses. The switch statement replaces a series of if/ else/ elseif statements and makes the code more straightforward and readable.Īn everyday use of the switch statement in Craft CMS and Twig is outputting Matrix field data. Craft CMS’s implementation of switch is custom and not part of the core Twig library.īut the switch statement is common in most languages, especially those somewhat rooted in C. However, if you are using Craft CMS, you also have access to an additional control flow option: switch. For choice in control flow in Twig, we only have if and its siblings else and elseif.
0 Comments
Leave a Reply. |