In demand

ad1

Thursday, September 17, 2015

Blogger Templates: How to use modulo

Blogger is a free blog publishing service from Google that allows multi-user blogs. The blogger template system is in XML format/language. If you want to edit or create a blogger template then you you have to learn HTML, CSS and XML and some basics of JavaScript. One of those basics is the use of the modulo operator in a loop.

Mod or modulo just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2. It is used in programming as the operator %.
Using % will be best described by an example code. It may be useful when you want to do something for every N-th loop.
For example, if you want to show the labels on your blog post and show 3 labels on each line, you can do like this:
              
  <b:loop values='data:post.labels var='label' index='idx'>              
   <data:label.name/>         
     <b:if cond='data:idx % 3 == 2'>
    <br /> <!-- this will appear after every third label-->
     </b:if>    
</b:loop>

This code puts <br/> for every 3rd label. The "index" variable of the loop starts from zero and is incremented for each loop (0, 1, 2, ...). So every 3rd index modulo 3 becomes 2. The "index" variable of the loop was also recently added to the blogger markup language.

How it works

Remember in whole number calculation if the dividend cannot be divided or is larger than the divisor then the dividend is seen as the remainder. e.g

(dividend  % divisor = remainder/dividend) == comparison //remainder/dividend is compared

In a loop the first occurrence of the equality asked for will be the first action. So asking for  "== 2" in your code will cause action when ever "2" is seen regardless of how it gets there.


(8   % 3 = 2) == 2 // remainder is 2 so action is taken
(7   % 3 = 1) == 2 // no action 
(6   % 3 = 0) == 2 // no action 
(5   % 3 = 2) == 2 // remainder is 2 so action is taken 
(4   % 3 = 1) == 2 // no action
(3   % 3 = 0) == 2 // no action
(2   % 3 = 2) == 2 // no remainder but dividend is 2 so action is taken
(1   % 3 = 1) == 2 // no action 
(0   % 3 = 0) == 2 // no action


Sometimes programming beginners get modulo confused with modulus equations used in engineering. Programming is not all high level math and intricate algorithms. Sometimes it helps to think in the simplest of terms before thinking that something is too complicated.

Today's Links

Post a Comment

Print this!