So let’s take a look how Miva Merchant uses While Loops. If you’re familiar with While Loops in any other programming language it’s very similar within Miva Merchant. A While Loop tests for if a condition is true. If that condition is true, it executes the loop, if not, it breaks out of the loop. Let’s dig into this code a bit and see what it does.
So here I have:
So here I’m testing if g.counter, which is a variable, is less than or equal to 10 and counter is here, mvt:assign. Counter is equal to the value of 1. So what’s going to happen is, it’s going to hit the while loop and g.counter is going to be 1. If 1 is less than or equal to 10 it’s going to execute everything that’s in the loop. So right now I’m just outputting “Hello World!” Then, because we’re testing to see if counter is less than or equal to 10, we also need to do something with counter or else it would always be 1 and this would always be true and it would create an infinite loop. So here, before we get to the end of the while loop, we need to increment counter. We can do that through mvt:assign where we have the variable counter. We’re saying g.counter + 1. That will increment it to 2 after the first iteration and it comes back to the top of the loop and it will reevaluate this statement here to see if it’s true. If it is, it will continue into the loop and continue executing. Let’s bring this over to Miva and see what happens.
Here I’m on the CTGY page, Category Display and I’m looking at the header and the footer. I’m going to paste this code in, hit the “Update” button, go back to my category page on the front end and hit “Refresh” and you’ll see “Hello World” gets output ten times. It’s exactly what we expect.
While Loops are a very powerful program tool and are a great addition to the Miva Merchant template language. There are two other tags that are available in a while loop that I want to talk about. The first one is while stop. The while stop tag allows you to stop the loop from executing any further. Usually you’ll use it within a condition. If some condition is true, stop the loop, exit and continue on the next line of code.
The while continue is similar except it doesn’t stop the loop altogether. What it does is it returns the program flow to the top of the loop. This is also usually used in a condition. If some condition is true, set some variable, review some action and continue back to the top of the loop and continue on. While loops are relatively new to the Miva Merchant template language, but if used correctly, can be very powerful and give you a lot of flexibility.