The Ultimate Mustache Tutorial

Learning Mustache is a lot faster if you understand properly what it’s all about and learn the underlying concepts. You’ll grasp a firmer understanding of Mustache by going through this tutorial, than by directly diving into the official docs, which often seem confusing at first.

What is Mustache?

The first thing to learn is that Mustache is NOT a templating engine. Mustache is a specification for a templating language. This specification can be found here, but don’t read that just yet. You’re not ready yet.

The idea is, that you write templates that adhere to the Mustache specification, that then can be compiled / rendered to create an output.

What’s a Templating Language and what’s it for?

Let’s say you want to send the same email to 100 people, except you want to personalize the salutation with their respective first names. You could replace the first name by some placeholder:

Dear *|FNAME|*

I hearby blablabla ...

Here I have invented (=stolen it from Mailchimp) a syntax for a placeholder: *|FNAME|*

The mustache syntax looks a bit different. This case would be covered by the following template:

Dear {{fname}}

I hearby blablabla ...

As you can see, in Mustache we have curly braces for placeholders, which look like a mustache when rotated 90 degrees clockwise:

Hence the name of the language. There’s more to the Mustache than that, but before diving any deeper into the language, it’s useful to first cover another concept.

By simply having specified a templating language and having written a template doesn’t produce 100 emails for me. Much like with a programming language, just learning the language doesn’t actually mean you know how to run a program. For example you might read in your first JavaScript tutorial that ” var x = 5 + 3 ;” is JavaScript, but you might not know exactly how you could run the code. Similarly with Mustache, you might learn about the language in a tutorial, but have no idea how to actually convert your templates to an output. Or to put it differently: How the heck can I create my 100 emails from 1 single Mustache template? You’ll need a …

Templating Engine

So once a syntax aka. templating language is defined, you need a tool that fills the placeholders in the template(s) with actual data and produces an output. This is called a templating engine:

To strech this point again, Mustache is not the templating engine. It’s the specification for how the template file must look like.

Or to come back to the example with programming languages. Mustache is the language. Not the execution environment. You can learn about the language in a book. But to actually use the language, you’ll need a computer and something that can interpret and run your code. The programming language JavaScript, for example can be ran and interpreted by Firefox, Chrome, Microsoft Edge and Safari, but they all use a different underlying engine to interpret and run it.

What’s the Templating Engine for Mustache?

Like for JavaScript there, isn’t just one thing that can compile Mustache. There’s a multitude of tools out there that can take a Mustache Template, some input data, and produce an output. The multitude of tools is actually overwhelming. There are tools that do their job well. And then there are obsolete ones that are badly maintained and don’t actually adhere to the Mustache specification. So which one should you choose from the multitude of options? The answer is: It depends on where and how you want to use Mustache. I will make some examples here, but I encourage you not to get lost in the actual links to those tools, but rather stick with the tutorial. When you leave now, you’ll be into the nitty gritty of how to use one tool without having the greater picture.

Example 1: You have a Java server and want to send out emails to users. So you use our Mustache Template from above for the emails and extend it a bit. So now you’d like to tell your Java code “hey, I’ve got a mustache template and 3 users that go by the name of [“Hans”, “Gertrude”, “Fritz”], can you send them a welcome mail”? Then your best bet would be to use the most popular Mustache Engine written in Javahttps://github.com/spullara/mustache.java . Why? Because you have the data already in your Java code. The Mustache template file you can load through regular I/O:

// DOESN'T ACTUALLY WORK THAT WAY, BUT WAS EASIER TO ILLUSTRATE
String[] users = {"Hans","Gertrude","Fritz"};
for (String user : users) {
  String renderedEmail = mf.compile("emailTemplate.mustache", user);
  // ...then send email to user...
}

Example 2: You have a Python server and want to send an E-Mail. Pretty much the same as above, except that you’d use the most popular Mustache Engine written for Pythonhttps://github.com/defunkt/pystache.

Example 3: You just want to print 100 personalized invitations to your birthday party, but have no idea about coding whatsoever (which is obvious, since coders don’t have 100 friends). Then unfortunately Mustache is not a good choice for you, since literally all engines for Mustache are connected to a programming language. There isn’t such a thing that takes an excel list of invitees plus a Mustache template and generates 100 pdfs out of it. At least I haven’t found something like that. Even though in principle it would work since it’s just a case of [Template + Input Data = Output] there just aren’t enough people that want to build their birthday cards that way…

Actually, this example 3 was really educational. We’ve learned that all available Mustache engines are connected to programming languages. Which ones are the available languages?

Here’s a screenshot from the official Mustache page answering that question:

Okay, that’s quite a lot of implementations. As I mentioned, some are good, some are bad. For example, the one listed for “node.js” is not maintained and buggy, while the one under “JavaScript” actually also supports node.js. So as you can see this list isn’t the be-all end-all. Maybe some of the listed links are outdated. Maybe some other ones are not included. At the same time, it’s still the best list that I’m aware of.

So now that we’ve covered the conceptual basics, we can dive deeper into the Mustache Templating language. But let’s first repeat what we’ve learned so far:

  • Mustache is a templating language, not a templating engine
  • There are tons of implementations for mustache engines, but be careful when choosing since not all are good.

Learning the Mustache Template Syntax

Now for the rest of the tutorial you have two choices. Either you select a templating engine from above and learn how it works. Then you can actually test the examples on your machine, which makes it a bit more tangible. But since Mustache is just a language, you might also be lying at a beach right now, slurping your drink, and reading the rest of the tutorial.

The Basics

We already had saw our very first template above, but let’s repeat it in a similar fashion because it was so beautiful:

Hello {{planet}}
{
  "planet": "Earth"
}

We choose JSON to describe our data here, but this would depend on the engine you’re using.

The template plus the data would produce the output:

Hello Earth

Now depending on your tool this output might be stored in a variable of your program or written to the filesystem. For example, the JavaScript mustache engine has two modes: Either it can be used as a command line tool to produce files, or it could be used to dynamically render html files.

Like what you're reading?    Get the latest updates first!

No spam. Just great engineering posts.

Conditionals

In Mustache, there are no if and else statements and also no loops. That’s why they call it logic-less templating. At least they’re not directly represented as keywords in the templating language. It is however possible to conditionally show or hide a block of text. And this is how:

Mustache Template:

Hello
{{#myCondition}}
  la di da
{{/myCondition}}

Data:

{
  "myCondition": false
}

Output:

Hello

Loops through Arrays / Lists

Loops are also not represented directly in the mustache language, but indirectly via the data and how the mustache specification specifies behaviour when the data is an array.

Data:

{
  "users": ["Hans", "Fritz", "Geraldine"]
}

Mustache Template:

{{#users}}
  {{.}}
{{users}}

Output:

Hans
Fritz
Geraldine

If you want all names on the same line, you’ll have to write {{#users}}{{.}} {{/users}} on one line in the template (and put a space in there for legibility).

The elements could also be objects instead of strings, in which case access is given by just writing the property names into the brackets:

Data:

{
  "users": [{
    "name": "Hans"
  }, {
    "name": "Fritz"
  }, {
    "name": "Geraldine"
  }]
}

Mustache Template:

{{#users}}
  {{name}}
{{users}}

Output:

Hans
Fritz
Geraldine

Using templates inside of templates: “Partials”

One Mustache template can load another template. The specification states that this should work with the syntax

I am a template and I'm loading
{{> template2 }}
and now I continue

This works fine as long as template2 doesn’t require template1, then you’ll get an infinite recursion which your templating engine can’t handle.

Passing Data to Partials

Passing data to partials is actually a bit tricky and one of the things that took me the longest to figure out. It works like this:

{{#buttonOne}}
  {{> mybutton}}
{{/buttonOne}}
{{#buttonTwo}}
  {{> mybutton}}
{{/buttonTwo}}

and in the data you’d specify

{
  "buttonOne": {
    "title": "Cancel"
  },
  "buttonTwo": {
    "title": "Save"
  }
}

In the partial there could be the code

<button class="my-cool-button">{{title}}</button>

The result would print

<button class="my-cool-button">Cancel</button>
<button class="my-cool-button">Save</button>

Comments

Comments begin with an exclamation point and are ignored. The following template:

<h1>Hello{{! ignore me }}.</h1>

Will render as follows:

<h1>Hello.</h1>

Comments may contain newlines.

Summarized Learnings

Grasping the concepts at first isn’t easy because there are so many different implementations of Mustache and they’re often confused with the actual Mustache specification. Yet through a clear separation, the Mustache language can be learned independently, and then the skills can be used together with a carefully chosen engine (since not all of them are good or adhere to the official Mustache specs). Thanks for reading the tutorial, I hope you learned a lot, don’t forget to subscribe if you’re interested in Web Development and share the post with friends!

 

Host websites with high availability and low latency for less than 1$/month, SSL included

I’ve been deploying static websites the wrong way all of my life. My procedure used to look like this:

  • Choose a server (EC2, Digitalocean) in a region (US, Europe, …)
  • Set up some nginx / apache configuration
  • Maybe add SSL through letsencrypt

I’ve always been aware that there are several drawbacks to this:

  • The smallest EC2 / digital ocean instances cost ~5$ which is quite a lot if you have many websites.
  • To make this cheaper, you start putting everything on one server (e.g. one ec2 small instance for 20$ / month), but if this instance crashes ALL your websites are down. You’ll have a very fragile availability.
  • By selecting a server in a specific region, the other regions have high latency
  • Adding SSL is kind of a pain, even if it’s free through letsencrypt
  • It’s not scalable
  • You need to mess with complicated config files from nginx / apache and need to ssh into your instance.

I’ve just never been aware that there’s a much better and easier solution!

The solution is called … (drumroll) … : AWS CloudFront.

Or to be less product specific, the solution is called: Put a CDN in front of some highly available data store.

Here’s what that means:

Your users will access the content through servers in the region closest to them.

This eliminates all of the previously mentioned drawbacks:

  • It’s cheap: AWS charges less than 1$/month for this setup
  • It’s got high availability: S3 has 99.9999999% uptime (I’ve randomly added 9’s)
  • It’s got low latency: Content is served through the data center closest to you.
  • You get a free SSL certificate from AWS that you can easily, no config file hacking.
  • AWS takes care of scaling for you
  • It’s simple to set up & deploy!

How to set up AWS CloudFront

AWS CloudFront is pretty simple to set up, but there are a few pitfalls, so here’s a tutorial with pictures to guide you.

Step 1: Host website with AWS CloudFront

Go to https://console.aws.amazon.com/quickstart-website/home; you also have that link on your dashboard.

Next, fill out the wizard:

and hit create. Your website needs to have an index.html file for this to work.

Tada. You have a working hosted website at some crazy url.

Step 2: Setup domain

Hit “Buy domain” on the website dashboard. This is the right button even when you’ve already bought you’re website through Route 53.

If you already have a domain, you can simply select it here:

Step 3: Set up SSL

Back on the website’s main page, select “Manage settings in Amazon CloudFront”:

There, click edit:

and select Custom SSL Certificate:

If you don’t have one yet, you can request a new one. It’s easy to set up, but you’ll need to have a working email address for the domain. E.g. when you want to set up example.com, you need e.g. admin@example.com to be working. I’m not going too much into detail here, since that’s a topic on it’s own.

You can also forward HTTP to HTTPS in the CloudFront > Behaviors Tab: Edit the default switch to “Redirect HTTP to HTTPS“.

Once the certificate has been issued and connected, SSL works:

Step 4: Pretty URLs and Subdirectories

By default, the files are hosted as they are: example.com/articles/my-article.html. Now how can you get rid of the html extension? You can either just remove the html extension or have a folder example.com/articles/my-article/index.html.

Unfortunately, there’s also one setting that needs to be changed for this to work. Head over to s3 > website bucket > properties > static website hosting and copy the “Endpoint” URL:

Then in Cloudfront > Origins

select the right website and hit edit, then replace the “Origin Domain Name” with what you’ve copied from the S3 bucket (without the http://).

Congrats, you’re all set up!

Step 5: Deployment

It’s a bit annoying to always have to upload a zip if you’re more the command line type of guy. Fortunately, it’s still possible to upload through command line with AWS cli:

aws s3 cp dist s3://<bucket-name>/ --recursive

You’ll need to set up IAM for this to work. Create a new user, give him S3 access, and hit:

aws configure

once the aws command line cli is installed.

Additional Tips & Tricks

There are a few gotchas you’ll have to be aware of when setting up CloudFront.

Forwarding the Naked (Apex) Domain to the WWW domain

In order to achieve a forward from https://example.com to https://www.example.com you’ll have to use a really weird workaround: Create a new S3 bucket with the name example.com. It HAS to be example.com, you can’t give the bucket any other name. Then in properties > static website hosting redirect all requests:

Finally, in Route53 resolve example.com (or here tsmean.com) to this S3 bucket:

If the S3 bucket name IS EQUAL TO THE RECORD NAME, the S3 website bucket should show up when you select Alias Target. That’s it, that way requests to the naked (apex) domain can be forwarded to a www domain.

Cache Invalidation

If you’ve followed the “one server deployment paradigm” so far, you’re probably used to seeing your changes visible immediately after deployment. This is not the case when using AWS CloudFront. Since it’s a distributed system with servers at edge locations that cache your assets, those caches have to be invalidated first. AWShas two articles on this, first http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html and second http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ReplacingObjectsSameName.html.

They advise you against using their built-in cache invalidation mechanism since it becomes expensive above a certain number of requests. However, this free limit is 1000 requests per month as of August 2017. That’s more than enough for most people since you can declare wildcard paths and those are counted only once, even if thousands of requests are made! So you could just specify “*” as invalidation and your cache is cleared with one request:

I personally prefer this to versioned object / directory names since I find it easier.

You can also easily include this into a deploy script, that could look like this:

#!/usr/bin/env bash

# Prerequisits:
# 1) AWS CLI installation (pip install awscli --upgrade --user)
# 2) AWS CLI Login ("aws configure")
# 3) aws configure set preview.cloudfront true

CDN_DISTRIBUTION_ID="<replace with your cloudfront ID>"
S3_DIST="s3://<replace with your bucket name>/"

aws s3 cp <replace with your dist folder location> $S3_DIST --recursive
aws cloudfront create-invalidation --distribution-id $CDN_DISTRIBUTION_ID --paths "/*"
echo "Done!"

Single Page Applications

If you’re hosting a SPA (Single Page Application), you’ll run into the problem that upon reloading a non-root page (e.g. bla.com/team), you’ll get an error. To fix this, you have two options.

  1. In Cloudfront:
    – Go to Error Pages tab, click on Create Custom Error Response:
    – HTTP Error Code: 403: Forbidden (404: Not Found, in case of S3 Static Website)
    – Customize Error Response: Yes
    –  Response Page Path: /index.html
    – HTTP Response Code: 200: OK
  2. https://stackoverflow.com/a/16877231/3022127

Changing the URL (in case you need to)

If you ever want to migrate, e.g. from dev.bla.com to test.bla.com, you’ll need to:

  1. In Cloudfront, add a cname. To do so, edit the General Settings, it’s the first tab.
  2. Change in Route53
  3. Update AWS_WEBSITE_DOMAIN_NAME und S3 > website bucket > properties > tags. (for the sake of completeness)

Compressing Assets / Gzip

In order to speed up your page, it’s a good idea to compress your assets. To do so

  1. Go to CloudFront > Behaviour Tab.
  2. Select the Default Behaviour and click Edit
  3. Select “Compress Objects Automatically

Checklist

Here’s a short checklist whether you’ve completed all important steps:

  • http://www.your-domain.com is working
  • https://www.your-domain is working (SSL)
  • http://your-domain.com is working (naked)
  • https://your-domain.com is working (naked, SSL)
  • https://your-domain.com/subdirectory is working
  • Compression is enabled

Conclusion

Compared to AWS CloudFront, deploying to single instances just feels hacky and wrong now. It’s simpler, cheaper and safer with AWS CloudFront. It’s the solution I’ve always wanted, but didn’t know existed. Hope this tutorial helps someone!

How to write a typescript library

I was a bit annoyed when googling for the topic. After a while when I had scratched together all the information, discarded the outdated one and inserted the missing bits, I decided to spread the knowledge. I went forward and created

Check it out.

You can also skip the tutorial and find the final demo library at https://github.com/bersling/typescript-library-starter, but I’d really recommend reading the tutorial or at least skimming through it!

A short summary, sort of just like the “difference to a normal project” would be this:

  • Add declaration: true to tsconfig.json
  • Export public parts via index.ts
  • Create a package.json, with the name your library should later have. Also point to the typings by using the “types” flag, for example: “types”: “dist/index.d.ts” in the package.json.
  • Configure .npmignore
  • run npm publish

 

Yet Another Install Guide For Raspberry Pi 3

 

I found the installation & setup of the raspberry pi to have quite a few pitfalls, so here’s my own guide for a headless Pi installed through a MAC.

Step 1: Format your SD Card properly!

Use the Disk Utility to format the drive (MS-DOS, Masterboot Record).

screen-shot-2017-01-05-at-00-26-55

When you then type diskutil list into your terminal, the SD Card should be formatted like so:

screen-shot-2017-01-02-at-01-45-39

It’s important that the type is DOS_FAT_32. Otherwise you might run into error messages like Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(179,2) later on. If it’s not yet formatted like this, you can try the following app (SDFormatter) https://www.sdcard.org/downloads/formatter_4/

Step 2: Download the OS

On https://www.raspberrypi.org/downloads/ you find the images available. I strongly recommend to use the Raspbian Lite image (for headless use of the PI!), unless you know what you’re doing. For example, if you install Ubuntu Snappy, you’ll have no chance to follow any tutorial later on, as they all rely on apt-get install, which is not available on “Snappy”.

Step 3: Install the image

diskutil unmountDisk /dev/disk<NUMBER>
sudo dd if=<myfilename.img> of=/dev/disk<NUMBER> bs=1m

where <NUMBER> refers to the disk number of the SD Card you see when you run diskutil list. The installation takes a long time (~1h). It doesn’t display any verbose output, so you’ll just have to be patient. Once finished a success message is displayed:

screen-shot-2017-01-02-at-09-31-45

Step 4: Power UP & Enable SSH

Insert the micro SD Card into your PI, then connect the following things:

  1. Ethernet / LAN cable
  2. Monitor (only during setup)
  3. Keyboard (only during setup)
  4. Power

It seems to be possible, yet troublesome, to enable ssh without a monitor / keyboard, so here’s the way with keyboard + monitor. Once started up, login to the Pi using user pi and password raspberry. Then type sudo raspi-config and go to “Interfacing Options”. There, enable SSH and reboot the PI.

Step 5: Login via SSH

First, you’ll have to find your PI on your network. If you connected a monitor, you’ll see the IP of the PI in the boot log. If not, you can find it’s IP by typing arp -a and checking which devices might be the pi.

Then login using ssh pi@<Pi’s IP>

The password is raspberry.

Step 6: Passwordless Access to the PI

On the PI:

cd ~
install -d -m 700 ~/.ssh

On your mac:

cat ~/.ssh/id_rsa.pub | ssh pi@192.168.192.64 'cat >> .ssh/authorized_keys'

(replace the IP by the IP of your PI).

ES6 Modules and Typescript

The whole thing is still pretty crazy as of August 2016. If you want to develop your frontend with typescript, you’ll probably encounter all of those “things”:

bower, npm, node, grunt, gulp, typescript, tsconfig, tsc, transpile, es6, javascript2015, module, module loader, import, export, require, systemjs, amd, umd, commonjs, babel, traceur, browserify, webpack…

Those are just some things mixed together in a wild manner, but the sheer amount of tools & concepts is nuts.

Okay, so what’s the whole point anyways? You want to use typescript and this usually goes hand in hand with the import / export syntax. Import / export is from “es6” = “javascript2015”, but this javascript version is not fully supported by most browsers yet. And you don’t want to build your production app in a language that won’t run in most browsers. So what can you do? You can use something that does the following:

MAP ES6 to ES5

Who can do this? Babel, typescript and traceur for example. Forget about babel and traceur and use typescript.

But if you use import / exports in your code (i.e. modules) the es5 generated by typescript will not run by itself. Here you have two choices:

  1. Don’t use modules.
  2. Use a module loader.

Unfortunately there is no way around using a module loader, if you want to use import / export in your code. If you already have a large app, you have to think this through, as introducing modules implies quite a lot of refactoring. The rest of this article assumes you decided to use modules. A possible and not all-too-stupid choice for a module loader is SystemJS.

So, in summary what happened until now:

  1. ES6 has “cool new features you want to use”, but browsers don’t support them yet. (But probably you were kinda dragged into this by starting with typescript)
  2. In order to use es6 syntax today to develop a production ready app, we thus somehow need to map es6 to es5. Typescript does this for us.
  3. The es5 generated by typescript doesn’t run by itself, in case you are using modules (i.e. there is import / export in your code). In order to load those modules, you’ll need a module loader like SystemJS.

Here’s a minimal “app” that is built around those concepts:

index.html

<!DOCTYPE html>
<html lang="en">
 <head>
 <meta charset="utf-8">
 <title>Typescript Modules</title>
 
 <!-- get systemJS from somewhere -->
 <script src="https://code.angularjs.org/tools/system.js"></script>
 </head>
 <body>

 <script>
 // set our baseURL reference path
 System.config({
 baseURL: './'
 });

 // loads /js/main.js
 System.import('main-module.js');
 </script>

 Open your js console.
 </body>
</html>

main-module.ts

import {someVar} from "./some-es6-module.js"

console.log(someVar);

some-es6-module.ts

export var someVar = "Hello World";

tsconfig.json

{
 "compilerOptions": {
 "module": "system",
 "target": "es5"
 },
 "files": [
 "main-module.ts",
 "some-es6-module.ts"
 ]
}

To make it run:

  1. Put all those files into a folder or download them from https://github.com/bersling/minimal-typescript-es6-module-app/tree/master.
  2. Get the typescript compiler and run tsc.
  3. Start a server with python -m SimpleHTTPServer and see the app at 127.0.0.1:8000

Programming in LaTeX

If / else and for loop

Latex is turing complete, but it’s syntax can make it hard to really program. What’s especially confusing, is that oftentimes keywords are not followed by a space, but rather directly by a string. For example if you have the boolean variable foo, you can set it to true using the command footrue, which is a very weird syntax compared to foo = true what we’re used to… However, if you really want to, you can write if’s and loops and do all kinds of stuff… Following is a short tutorial on how to do so.

Booleans and If / Else Statements in Latex

One of the most fundamental parts of any programming language is arguably the boolean data type and it’s logic counterpart the if/else statement. Booleans are part of the latex core, as well as of packages such as the ifthen package.

Booleans and If / Else Without a Package (Option 1)

Booleans can be used in Latex without the use of any packages. However, the syntax is quite cumbersome.

Declaration:

\newif\iffoo %Declaration

Assignment:

\footrue %Sets foo to true
\foofalse %Sets foo to false

Check:

\iffoo
...
\else % else is optional, you can leave it out
...
\fi

Usage example:

\documentclass{article}

\begin{document}
\newif\iffoo %Declaration, defaults to false

\iffoo
text 1
\fi

\footrue % Set foo to true...

\iffoo
text 2
\else
text 3
\fi
\end{document}

Output:Screen Shot 2016-05-22 at 18.45.22

Booleans with the Ifthen Package (Option 2)

When someone is not comfortable with the syntax of the latex core for booleans, he or she might consider to use the ifthen package.

Requirements:

\usepackage{ifthen}

Declaration & Assignment:

\newboolean{boolvar} %Declaration, defaults to false
\setboolean{boolvar}{false} %Assignment

Check:

\boolean{boolvar}

Usage Example:

\documentclass{article}
\usepackage{ifthen}
\begin{document}
\newboolean{boolvar} % Declaration, defaults to false
\ifthenelse{\boolean{boolvar}}{text1}{text2} % If/else with boolean
\setboolean{boolvar}{true} % Assignment
\ifthenelse{\boolean{boolvar}}{text3}{text4} % If/else with boolean
\end{document}

Output: Screen Shot 2016-05-22 at 18.18.29

Integers and Loops in Latex

While integers and loops are an integral part of any programming language, it only occurs to few people to use those concepts in latex outside of the enumeration or itemize environments. Nonetheless it can be done, and here is how.

Integers / Counters

Right next after booleans, or even before them, one usually learns about the data type integers. Latex again has a very peculiar syntax for handling them.

Declaration:

\newcounter{mycounter} %initialized with 0

Assignment:

\setcounter{mycounter}{2} %sets counter to 2

Increment:

\stepcounter{mycounter} % increases mycounter by 1

Get value for programming (e.g. in ifnum condition, see below):

\value{mycounter}

Get value for text output in document:

\themycounter

Adding a number to a counter:

\addtocounter{mycounter}{4}

Adding a counter to a counter:

\addtocounter{mycounter}{\value{myothercounter}}

To compare two counters in an if-clause, the \ifnum-keyword is used:

\ifnum\value{mycounter}>3
Cool beans! % this is only printed if mycounter is larger than 3
\fi

Note: There are also counters in TeX (as opposed to LaTeX), so you might encounter code like \newcount\mycounter elsewhere. The difference between \newcount (TeX) and \newcounter (LaTeX) is minuscule, so make sure you don’t get confused since e.g. calling \value{mycounter} on a counter initialized by \newcount\mycounter will throw an error!

Finally, here’s a complete usage example:

\documentclass{article}
\begin{document}
\newcounter{mycounter} %declare counter, initialized to 0
\themycounter %prints 0
\setcounter{mycounter}{4} %mycounter is now 4
\themycounter %prints 4
\addtocounter{mycounter}{4} %adds 4 to mycounter
\themycounter %prints 8
\addtocounter{mycounter}{-2} %subtracts 2
\themycounter %prints 6
\addtocounter{mycounter}{\value{mycounter}} % adds mycounter to itself
\themycounter %prints 12
\stepcounter{mycounter} % increments mycounter by one
\themycounter %prints 13

\ifnum\value{mycounter}>11
Well yes, \themycounter\ is larger than 11...
\else
...thus this is neverprinted
\fi

\roman{mycounter} %prints mycounter in roman numbers
\end{document}

With it’s glorious output: Screen Shot 2016-05-22 at 20.59.28

Next, we’ll cover how loops can be implemented in LaTeX.

For Loops Without a Package

Since we now have the basics in place to create an integer, compare integers using the operators =, < and > , all we are missing to write a loop is a keyword to do so. The syntax for this is:

\loop \ifsomething
...
\repeat

So a full example would be:

\documentclass{article}

\begin{document}
\newcounter{mycounter}
\setcounter{mycounter}{2}

\loop
\ifnum \value{mycounter} < 5
hello \themycounter,
\stepcounter{mycounter}
\repeat

\end{document}

Output:Screen Shot 2016-05-22 at 19.50.36

For Loops With the forloop package

Requirement:

\usepackage{forloop}

Usage example:

\documentclass{article}
\usepackage{forloop}
\begin{document}
\newcounter{ct}
\forloop{ct}{1}{\value{ct} < 5}{\arabic{ct} }
\end{document}

Output:Screen Shot 2016-05-22 at 17.53.37

For Loops With the pgffor Package

If you prefer a more Python-like syntax, the pgffor package might just be for you. I took the examples from this Stackoverflow answer.

Example Snippet 1:

\foreach \n in {0,...,22}{do something}

Full Example 2:

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\foreach \n in {apples,burgers,cake}{Let's eat \n.\par}
\end{document}

Output: Screen Shot 2016-05-22 at 20.25.45

While Do in Latex with the Ifthen package

Requirement:

\usepackage{ifthen}

Usage Example:

\documentclass{article}
\usepackage{ifthen}
\usepackage{pifont} % for the ding
\begin{document}
\newcounter{ctra} % declare counter, is set to 0
\setcounter{ctra}{3} % set counter to 3
\whiledo {\value{ctra} < 7}
{
 \thectra {\large \ding{111}} % the + counter name prints a counter
 \stepcounter {ctra} % increase the counter by one
}
\end{document}

Output:Screen Shot 2016-05-22 at 18.05.12

Floating Point Numbers (Lenghts in Latex…)

If you read the previous paragraphs, you should get the gist of it by now, so I’ll just provide an example for this one:

\documentclass[varwidth]{standalone}
\begin{document}
\newlength{\mylen} %Declaration
\setlength{\mylen}{3.14pt} %Assignment
The number $\pi$ is approximately \the\mylen\ (think away the pt...).

\addtolength{\mylen}{0.0016pt} %Operator
To be (2 digits) more precise, it's rather \the\mylen.

\settowidth{\mylen}{Text} % measures the width of "Text"
"Text" is \the\mylen\ wide... Crazy stuff.
\end{document}

Which yields the following output:

Screen Shot 2016-05-22 at 22.27.40

Comparison to a Normal Programming Language

Let’s compare the crazy LaTeX syntax to a normal language like Java. The following table can also be used for reference.

LaTeXJavaMeaning & Notes
\newif\iffooboolean foo;Declare a boolean. Defaults to false in LaTeX and null in Java
\footruefoo = true;Set foo to true
\foofalsefoo = false;Set foo to false
\iffoo
%do this
\else
%do that
\fi
if (foo) {
//do this
} else {
//do that
}
If-else statement
\newcounter{n}int n;Initialize integer. Defaults to 0 in Latex and null in Java.
\setcounter{n}{2}n = 2;Set n to two
\stepcounter{n}++n;Increases n by one
\value{n}n;Get value of n for calculations
\then %this is actually a \the immediately followed by n...log.info(Integer.toString(n));Get value of n for print
\addtocounter{n}{4}n += 4;Add 4 to n.
\ifnum\value{n}>12
%do this
\fi
if (n > 12) {
//do this
}
Check if n is larger than 12.
\ifnum\value{n}=12
%do this
\fi
if (n == 12) {
//do this
}
Check if n is equal to 12.
\newcounter{mycounter}
\loop \ifnum\value{mycounter}<5
\themycounter
\stepcounter{mycounter}
\repeat
for (int i = 0; i < 5; i++) {
log.info(Integer.toString(i));
}
For Loop. Prints 0 1 2 3 4
Alternative:
\usepackage{pgffor}
\foreach \n in {0,...,4}{do something}
\newlength{\mylen}float mylen;Create a floating point number. Latex initializes this to 0.0, Java to null.
\setlength{\mylen}{3.14pt}mylen = 3.14;Sets length to 3.14pt in latex and to 3.14 in Java. Since Latex is for typesetting the length must have a unit.
\the\mylenlog.info(Float.toString(mylen));Get mylen for print
\mylenmylen;Get mylen for calculation
\ifnum\mylen<1
%do this
\fi
if (mylen < 1) {
//do this
}
Compare mylen to another number

This article is based on this article here, so thank you Matthias for working this out!