The Now Platform® Washington DC release is live. Watch now!

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
SlightlyLoony
Tera Contributor

Sometimes you need to be a little obsessive-compulsive in your HTML rendering, such as when you want to make a list of something. You need to do the same thing, over and over again — you need repetition, iteration, or some other such loopy thingamabob. I've already introduced you to a teensy bit of this with the first Jelly example I showed you:


<?xml version="1.0" encoding="utf-8"?>
<j:jelly>
      <j:set/>
      <j:while>
           
Test
              <j:set/>
      </j:while>
</j:jelly>


That's the while loop that every programmer is familiar with (hopefully!). But wait! There's even more loopy Jelly thingamabob goodness!

When you need to iterate over a collection of things, the Jelly forEach tag is your friend. For instance, here we're iterating over an array of CSS color names:


<?xml version="1.0" encoding="utf-8"?>
<j:jelly>
      <g:evaluate>
              var colors = ['Red', 'Black', 'Blue', 'Brown', 'CadetBlue', 'DarkGreen', 'DeepPink'];
      </g:evaluate>
      <j:foreach>
           
Color: $[SP] ${jvar_color}
      </j:foreach>
</j:jelly>


Don't worry about that evaluate tag at the moment; it's just creating an array of color names for us. We'll get into much more detail about it in a later post. For now, just look at the forEach tag. The items attribute is where you specify the collection (in this case, an array) of things to iterate over. The var attribute is where you specify the name of the variable that will contain each item from the collection in its turn. The array of color names has seven colors in it, so that forEach loop will execute 7 times, once for each color. The first time through, the variable jvar_color will contain "Red", the next time through "Black", and so on.

Now look at the line after the forEach tag. Here's where we're actually doing something useful (well, maybe). The first time through the loop, when jvar_color equals "Red", the JEXL expressions will evaluate into this HTML:


           
Color:     Red


This is an example of how the JEXL expressions can be used to directly render HTML. It's worth taking a few minutes to make sure you really understand what's happening in there. In later posts you'll see how you can use information from your ServiceNow instance's database to do similar sorts of things. Some of these will look complicated, but in the end there's really only two things going on: (1) we're making decisions about what HTML to render, or (2) we're getting data to be part of the HTML we're rendering.

Now you have all the tools you need to build trully obsessive-compulsive Jelly!

7 Comments