Skip to content

Instantly share code, notes, and snippets.

@stevekrouse
Last active December 18, 2015 20:59
Show Gist options
  • Save stevekrouse/5844325 to your computer and use it in GitHub Desktop.
Save stevekrouse/5844325 to your computer and use it in GitHub Desktop.

Tips and tricks for understanding this document:

  • The dollar sign refers to the terminal prompt. The text after it is what you type in. The lines without $ is the terminal's response. (This holds except for in telnet, in which inputs and responses unfortunately look the same. But fortunately, you're smart.)
$ ping google.com 
PING google.com (74.125.239.128): 56 data bytes</code>

The Web and the Internet

Everyone knows what the web/internet is, but nobody really knows what makes it work. The blame for this lies squarely on the web browser. The modern day web browser combines HTML, Javascript and CSS documents seamlessly into a beautiful package that the end user couldn't tell from a interactive movie. This document serves to uncover the mystery shrouding internet technologies.

Words that programmers throw around, like JSON, AJAX, callbacks and JQuery, are not difficult concepts in reality. But the key to understanding them is not in learning Rails: that's like taking a Financial Derivatives class to understand arithmetic. Understanding the foundations of the internet allows one to teach oneself as many ancillary web technologies, like Rails, down the line. Once you understand the way in which you have to frame your thoughts for web programming, it merely becomes a translational problem: how to I convert my thoughts from English into Rails, Django, Node, or what have you. First of all, we shall start by making a distinction between the web and the internet.

The Web

The web is a collection of HTML, Javascript and CSS documents that point to each other. You can think of the web as a spider's web of documents that exist in the clouds – we’ll get to the cloud later – that your web browser "crawls" across. web

For example, when you Google something, the result you get is an HTML page that contains links to other HTML pages. When you click on any of those pages, your browser "jumps" across the web and asks for those pages. Those pages, in turn, contain links to other HTML pages. The links are represented in HTML as <a> tags.

<a href="stevekrouse.com"> Check out my website! </a>

HTML pages don't only link to other HTML pages, but they also link to CSS and Javascript documents as well. These links are abstracted away by the browser, but behind the scenes the browser goes to "crawls" across the web to those links as well and downloads those pages in the background. Then, it uses the information it gets back from those ancillary pages to add to the page the user is looking at. We will see how this is done in a few sections.

HTML - HyperText Markup Language

HTML is the backbone technology of the seeable web. Everything that you see on the internet is HTML, whether it be a photo, text, movie, Facebook post, or Spotify song. HTML code looks the way it does for a few reasons: 1) it's tagging structure is human readable, 2) it's tagging structure is machine parsable, 3) the makers of HTML were designing a language for static documents – not dynamic web apps.

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <p> Hello <a id="world" href="world.com"> World </a>! </p>
    </body>
<html>

For contrast check out Angular.js, the MVC framework, that touts itself as what HTML would have looked like had it been designed for web apps. Scroll down on the Angular home page to see what HelloWorld looks like in an Angular app.

CSS - Cascading Style Sheets

For defining everything from letter-spacing to color to height and width, CSS is what makes HTML look good. You may have realized that HTML is literally just a tree or DOM (document object model). For example, the above HTML document is really just the following tree:

      |--head  
html--|
      |--Body -- p -- a

But somehow browsers can make this very un-sexy tree structure appear quite sexy and complex. This is due to CSS. CSS can tell each separate HTML element where to be, how big to be, what color to be, how to interact with the other elements on the page, etc. A CSS document looks like this:

body {
    text-align: center;
}
#world{
    color: blue;
}

First, I'm telling the text within the body element to be centered (within the context of the body, which in this case in the whole page). Next, I am referencing the id (id's are referenced with pounds (#); classes are referenced with dots (.) in HTML and CSS) of the world link and telling it to be blue. Pretty straight forward, huh?

CSS only gets complicated when you either 1) want to create responsive web pages (or pages that resize easily, like for a mobile phone, for example) or 2) you are creating a complex page with many different elements (in which case you may want to consider using SASS, a language that adds a thin layer of complexity over CSS and compiles down to CSS).

Javascript

Back when Mark Andreessen was on the other side of the table, he ran a little company called Netscape that built the first widely-used web browser. There, they developed Javascript to be the language of the web. Though it has little more in common with Java than its curly braces and semicolons, they probably chose to name it after Java because of the hipness of Java as the state-of-the-art web technology of the day. Here is generally what javascript looks like:

function hello() {
        alert("Hello World");
}

Go ahead and try it in your browser's console: right click anywhere in your browser, press "Inspect Element" and then click on the rightmost tab, "Console."

Inline CSS and Javascript

Although it usually makes the most sense to keep your CSS, HTML and Javascript separated in their own files, you can add Javascript and CSS right in the .html file.

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <p> Hello <a style="color:blue;" id="world" href="world.com"> World </a>! </p>
        <script>
            alert("Hello World");
        </script>
    </body>
<html>

Linking HTML to CSS and Javascript

Usually – unless you're building a crud app, like at a hackathon – the above code should never live longer than it takes to test out a new feature and then refactor the logic or style to its appropriate siloed file. So how does a browser know which CSS and Javascript files help support a given HTML file? Well, earlier I mentioned that the web is literally just a collection of documents that point to each other and this is no different: an HTML document has links that are not displayed to the user that tells the browser which supporting documents it also needs to download to display a given page.

<!doctype html>
<html>
    <head>
        <!--This is a comment. Comments, like JS and CSS links, are not displayed in the browser-->
        
        <!--A link to a stylesheet located in the same directory as the HTML page-->
        <link rel="stylesheet" type="text/css" href="mystyle.css">
            
        <!--A link to a Javascript file located in a folder called filepath-->
        <script type="text/javascript" src="filepath/filename.js"></script>
            
       <!--A link to JQuery, a popular Javascript library, hosted on Google's server-->
       <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    </head>
    <body>
        <p> Hello <a id="world" href="world.com"> World </a>! </p>
    </body>
<html>

As you can see above, similar to how you can link to images that are hosted either on your own server (in a local directory) or hosted elsewhere on the web, you can link to JS and CSS files locally or hosted. It's okay if you don't fully understand what "hosting" means just yet; that will be covered in the next section on the Internet.

Contrast a locally and remotely hosted image tage:

<img src="myfile/img.jpg"></img>
<!-- or -->
<img src="http://cloudapp.com/sakduf879.jpg"></img>

Also, it is key to note that the order that files are linked to in an HTML document is the order in which they are loaded by the browser. So if you load a file that calls a functioned defined in a file that loads after it, you may run into issues.

The Internet

The web is a collection of documents that point to each other in the cloud, but what is the cloud? The Internet (or cloud) is a collection of tens of thousands of networks.

Internet

The two backbone technologies of the internet are IP and DNS. IP addresses are the way computers identify themselves over the internet. They are simply a 32-bit number. You can read more about how we are running out of IP addresses here. The DNS (Domain Naming System) assigns names to IP addresses. So google.com, for example, doesn't really mean anything to my computer. It doesn't know where to go based on that information. So the first thing that happens when I type in google.com in my browser is that my computer goes to the DNS servers and asks, "What is the IP address for google.com?"

Exercise 1:

$ nslookup google.com
Server:      8.8.8.8
Address:    8.8.8.8#53

Non-authoritative answer:
Name:	google.com
Address: 74.125.239.133
Name:	google.com
Address: 74.125.239.128
Name:	google.com
Address: 74.125.239.134
Name:	google.com
Address: 74.125.239.135
Name:	google.com
Address: 74.125.239.130
Name:	google.com
Address: 74.125.239.137
Name:	google.com
Address: 74.125.239.131
Name:	google.com
Address: 74.125.239.132
Name:	google.com
Address: 74.125.239.129
Name:	google.com
Address: 74.125.239.142
Name:	google.com
Address: 74.125.239.136

As you can see, sometimes for a large service like Google, there are multiple name to IP records stored and thus your browser has its pick. We can see which one our computer choses by pinging, or sending test packets to, google.com.

Exercise 2:

$ ping google.com
PING google.com (74.125.239.128): 56 data bytes
64 bytes from 74.125.239.128: icmp_seq=0 ttl=56 time=30.292 ms
64 bytes from 74.125.239.128: icmp_seq=1 ttl=56 time=32.152 ms  
64 bytes from 74.125.239.128: icmp_seq=2 ttl=56 time=23.744 ms

So I guess it chose 74.125.239.128.

A moment ago, I stated that IP addresses allow computers to identify themselves on a network. However, IP addresses are also what your computer uses to download google.com's HTML. This works because a magical type of computer, called a server, is located at the IP addresses corresponding to google.com.

Talking to Servers

The italics on "magical" a few lines above was sarcastic: servers aren't magical at all. They are just regular old computers with one caveat: a server is a computer that listens for connections on given ports.

// Listening to port 1337 in node.js
http.createServer(function (req, res) 
{
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

Or

# Listing to port 5000 in Flask
app.run(host='0.0.0.0', port=5000)

Or

// Listen on port 8080 in Java
serverSocket = new ServerSocket(8080);

In the above google.com example, the computers located at those IP addresses are listening on port 80 for connections from a user's web browser. 80 is the standard port for HTML connections, however connections can be made on other ports (as long as the server is listening for them on those ports). For exmpale, people typically use port 5000 or 8000 for server development hosting or 443 for HTTPS and 25 for SMTP (full list herehttp://en.wikipedia.org/wiki/Port_(computer_networking)). You can see what happens when we try to connect to google.com on a port it doesn't listen for:

Exercise 3:

$ telnet google.com 8000
Trying 74.125.239.132...
telnet: connect to address 74.125.239.132: Operation timed out

No matter how hard our computers try, it will never connect to a server on a port the server's not listening on. But it'll connect instantly to a port it is listening for:

Exercise 4:

$ telnet 74.125.239.132 80
Trying 74.125.239.132...
Connected to nuq05s02-in-f4.1e100.net.
Escape character is '^]'.

Notice how here I used one of the IP addresses for google.com and not "google.com." To telnet, this means basically the same thing (except for the fact that it has to make one less DNS lookup). Another thing you may have noticed in the above snippet is how I am connected to one of google.com's servers. The Escape character is '^]'. may give you a hint to the fact that I am now communicating directly with the server. If you're following along, go ahead and type some laksdjf;alskdf into the connection and hit enter twice. Were you surprised to see HTML code (among other things) come back at you?

$ telnet 74.125.239.132 80
Trying 74.125.239.132...
Connected to nuq05s02-in-f4.1e100.net.
Escape character is '^]'.
laksdjf;alskdf
HTTP/1.0 400 Bad Request    
Content-Type: text/html; charset=UTF-8
Content-Length: 925
Date: Tue, 18 Jun 2013 05:09:44 GMT
Server: GFE/2.0

<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
 <title>Error 400 (Bad Request)!!1</title>
<style>
*{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}
</style>
<a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>
<p><b>400.</b> <ins>That’s an error.</ins>
<p>Your client has issued a malformed or illegal request.  <ins>That’s all we know.</ins>
Connection closed by foreign host.

Turns out we got back a HTTP "Bad Request" response. I guess that means we should learn what HTTP is.

HTTP - Hypertext Transfer Protocol

A recurring theme of this tutorial is that the web speaks English. Sure its pretty terse English that probably wouldn't be advised for use when courting the opposite sex, but it's English all the same. To understand the subset of English that is HTTP, you merely need to understand the verbs GET and POST (and sometimes PUT, DELETE, and a few others but nobody really uses them). For example, if you decide not to follow my earlier advice, an HTTP request might look like:

GET /bar/hot/chick HTTP/1.0
GET /party/sexy/dude HTTP/1.1
POST /pics/hottie-from-last-night.jpg HTTP/1.1

Unfortunately the universe doesn't speak HTTP so the above calls won't work the way we'd hope. But on the bright side, HTTP really that simple.

Exercise 5:

When you type in wired.com/gadgetlab into Chrome, your browser get's wired's IP, launches up a telnet conversation with it, and the types GET /gadgetlab HTTP/1.1. Then your browser scans the HTML document, looking for links to CSS and JS files and makes subsequent GET requests for them, too. It does it's compiler magic to transform all of that information into one page and violia: we have wired.com/gadgetlab.

Go ahead and pop open telnet and type in a correctly-formed GET request. Then hit enter twice.

Headers

The main thing I'm glossing over here, however, is HTTP headers. Headers are what allow you to stay logged in to Amazon.com throught your order. Without headers, the only secure way you'd be able to stay logged in to Amazon through each page load would involve being required to re-login every time you clicked on another link.

Headers are also how a browser and a server communicate about things like, "Hey, I'm an iPhone" or "Hey, I'm using Chrome on a macbook" or even "The last time I downloaded this page was this date, has it been updated since then or can I just used the cached page I saved from last time?"

For both a user and a server, a general HTTP conversation with headers looks like this:

<initial line, different for request vs. response>
Header1: value1
Header2: value2
Header3: value3

<optional message body goes here, like file contents or query data;
it can be many lines long, or even binary data $&*%@!^$@>

Headers are just as easy to understand as HTTP. You literally just put the header name, a colon and then it's value. For example:

GET /some/path HTTP/1.1
User-agent: Mozilla/3.0Gold

And a response:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Set-Cookie: name1=value1; Expires=Wed, 09 Jun 2021 10:18:14 GMT
Set-Cookie: name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT

Ever hear of cookies before and thought they were some crazy complicated technology? Yeah, they are really just a simple directive for a browser to set a given variable to a given value. Then, every time a browser hits that url that stored that cookie in it, it adds the Cookie: name2=value2 header in all of its subsequent requests. So the next request to the above site would look like this:

GET /some/other/path HTTP/1.1
User-agent: Mozilla/3.0Gold
Cookie: name1=value1; name2=value2;

The expiring of cookies is pretty straight forward. One other thing to quickly note here is that all subsequent requests your browsers makes to other servers will remain unchanged by this cookie, however. So if amazon.com stores a cookie in your browser, your broswer won't give that cookie in a request to google.com, for example.

HTTP sessions, although a seemingly complicated technology is accomplished through these cookies. Amazon gives you a secret password in the form of a cookie that your browser uses with each subsequent request to stay logged in. It's basically like Amazon saying, "Hey recently-logged in user, the next time you see me again, tell me this secret password so I know who you are without you having to log in again." (This is why when you use incognito-mode, you are not logged in to any of the sites you normally are: your browser isn't sending the cookies that've been stored in it, so Amazon doesn't know who you are right off the bat.)

REST

The reason that cookies and sessions are even needed at all in HTTP is because of REST. Truth be told, REST is an unbelievably amazing system. It was built on the belief that the internet protocol should be stateless and also be built on a small number of verbs, like GET, POST, etc. Imagine, for contrast, if you had to interface with an infinity of arbitrary verbs like fbPOST or TWEET or instaPUSH. However, the stateless of HTTP, while simple, didn't take into account the need to store state for a service like Amazon. Thus sessions are really just a complete hack of cookies that the entire web has adopted.

Javascript

It is the best of languages and it is the worst of languages. There will be times when you $.ajax() the shit out of a project and love Javascript more than your mother and there will be times when you spend hours trying to make sense of its fucked up variable scoping. But, all things considered, the web wouldn't be the same without this transformative technology. (And if you ever can't stand it that much, there's always the Pythonic Coffescript to fallback on.)

Duck Typing

Javascript is a dynamically-typed scripting language. This means that types are associated with values and not with variables.

In Java you would say something like int number = 5 and then later if you tried to stuff "five" into number, like number = "five", the Java compiler would scream at you. However, Javascript doesn't let you tell it what types are supposed to be stored in certain variables. Thus the Javascript parallel is perfectly kosher:

Exercise 6:

number = 5
number = "five"

Consider this design choice in Javascript as its designers giving you more power, and thus development speed, but at the cost of more bugs and unpredictable code down the line.

Event Driven

Time is a bitch. This is doubly true in computer programming. Instructing a computer in what to do is hard enough – having to also take into account timing is a nightmare. Javascript helps alleviate this problem with something called a "callback." A callback is a function that is run after an initial function finishes running. A callback encapsulates the following logic: once you finish this process, take the information you've learned and do this second process with it. (The second process being the callback.)

This logical flow makes the most sense in the context of HTTP requests (i.e. when the page is finished loading, prompt the user to login), or in the context of button clicks or page animation (i.e. once this element is done moving, then start moving this other element; or, when a user clicks this button, take him to this page).

Exercise 7:

// Prints a success message
success = function() {
    alert("firstround.com was successfully loaded.");
}

/*  An example GET request in Javascript
 *  In english: once you've successfully received the HTTP response for /library,
 */ run the success callback.
$.get('http://firstround.com/library', success)

Pay no attention to the dollar sign ($) above. It is merely a library called JQuery that contains a function get. Other Javascript libraries are called in a similar manner. The Underscore library, for example, is called with underscore dot, like _.map().

AJAX - Asynchronous Javascript and XML

The javascript get function I used above to make a GET request used a technology called AJAX. In fact, the get function above is defined in the JQuery library as the following:

Exercise 8:

$.get = function(url, success) { $.ajax({
                                  url: url,  
                                  success: success,
                                        });
                               }

The strange looking syntax above is really just that: strange. It's nothing conceptually difficult. Curly braces in this context signify an object (in other contexts they can refer to function definitions or delimit code blocks, like in a for-loop).

Let's analyze the syntax: we are passing an Javascript object to the ajax function that contains url, and success variables (the left of the colon is the name of the variable; the right is the value). Javascript objects are a convenient way to pass in parameters to a function because it allows us as programmers to specify as few or as many parameters as they want. For example, the ajax function can also take data and dataType arguments, but because we are fine with the default values, we can safely leave them out. Here is the full definition of get:

Exercise 9:

    function(url, data, success, dataType) = $.ajax({
                                                url: url,  
                                                data: data,
                                                success: success,
                                                dataType: dataType
                                             });

JSON - Javascript Object Notation

After you deal with enough APIs, you will come to appreciate the warm, tingly feeling that programmers get when they work with a JSON API. JSON is a very human-readable standard that seamlessly converts to and from Javascript objects. A Javascript object is a very sexy thing.

Exercise 10:

obj = {
        key: val,
        sexy: true,
      }

Just look at those curves! But the real sexiness comes from the way you are able to grab out and put in variables within Javascript

Exercise 11:

    $ obj = JSON.parse('{
                          "key": "val",
                          "sexy": "true"
                         }');
    $ obj.key
    "val"
    $ obj["sexy"]
    true
    $ obj.newVal = "sup"
    $ obj["newVal"]
    "sup"

Notice how I access instance variables, or variables of an object, with dot or square-bracket notation interchangeably. An API call that returns JSON looks like this:

Exercise 12:

$ albert = $.getJSON('http://en.wikipedia.org/w/api.php?action=query&titles=Albert%20Einstein&prop=info&format=json')
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
$ albert.responseJSON
{
query: {
    pages: {
        736: {
            pageid: 736,
            ns: 0,
            title: "Albert Einstein",
            contentmodel: "wikitext",
            pagelanguage: "en",
            touched: "2013-06-19T21:36:32Z",
            lastrevid: 560027932,
            counter: "",    
            length: 102203
             }
          }
      }
}

It's just about that simple. By the way, this should sort of be blowing your mind: an API call is literally just a boring old GET request you've asked your browser to make for you a bajillion times a day. Prove it to yourself by typing in the above request into your browser.

You can access any of those returned fields with either the dot or bracket notation, like Albert.responseJSON.query.pages[736].title .

XML - Extensible Markup Language

A programmer's love for JSON stems directly from his or her hate for XML. XML is basically HTML (they have the same parent langauge SGML), but with an arbitary number of tags.

<api>
    <query>
        <pages>
            <page pageid="736" ns="0" title="Albert Einstein" contentmodel="wikitext" pagelanguage="en" touched="2013-06-19T21:36:32Z" lastrevid="560027932" counter="" length="102203"/>
        </pages>
    </query>
</api>

This sucks for the main reason that it doesn't play very nicely with Javascript – at least with the built in tools – and because it's ugly. We nerds may rock the hoodie a little too hard, but we do have standards.

Building a server

So far, we've discussed how you can talk to servers, but now we will briefly cover how servers talk back. Keep in mind that the most important part of a server is that it listens (and responds, if you ask it properly).

It's no accident that an HTTP path or URL so closely resembles UNIX file paths. Back in the olden days, servers just simply hosted all of the files of a given directory. A website would thus just be a directory tree of HTML, CSS and JS documents. And getting from web page to web page on a such a server was literally exploring that server's local directories.

Think about this for a second: the Internet was designed so that I can browse your file system. Now think about the complicated ways in which we have contorted the web to work for us today. This should clue you into why there are so many hacky solutions in web development.

Pop open a terminal window and start up an old-school server by running a simple Python module. This will create a server that hosts all the files in this current directory on your machine:

Exercise 13:

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...

Now go hop on over to 0.0.0.0:8000 (or localhost:8000) in your browser and explore. Once you get the idea of that, hop on over to telnet and talk to your own server. Dots should be connecting in your head as you do this. The Internet is really this simple!

Exercise 14:

$ telnet 0.0.0.0 8000
Trying 0.0.0.0...
Connected to 0.0.0.0.
Escape character is '^]'.
GET / HTTP/1.0    

Flask

Flask is a beautiful micro-framework for web servers in Python. If you want to quickly build a web server that has more logic than the static one above, Flask is par none. It is simple, elegant, easily readable and quite expressive.

flask.pocoo.org is your friend. If you're the kind of person that gets hot for a thoughtful documentation, be prepared to fall in love. Flask is an rare example of a tool in which it may make more sense to check the docs before Google. Gasp!

Getting set up in python

$ sudo easy_install pip
$ pip install virtualenv

Pip is the package manager of choice for python. Virtual environments are little playgrounds for you to install all of the random-ass python packages you want without them being installed throughout your machine.

Virtualenv

Exercise 15:

Set up a virtualenv, named "venv":

$ virtualenv venv

Jump into your new playground venv by sourcing, or running, its activation file:

$ source venv/bin/activate

Install all the python packages you desire:

$ pip install flask

Make sure you are within your virtualenv when running Python code.

$ python -i some_python_file.py

The -i is a flag for interactive: run this file and then let me interact with the resulting Python environment.

Hello World Server in Flask

Basic Python syntax can be picked up pretty quickly as its almost English. However, it took me months really feel the beauty of the language. Don't worry too much if the you feel sluggish in the syntax. It takes awhile to think pythonically

Exercise 16:

    # From the python package flask, import the "Flask" constructor
    from flask import Flask
    
    # Create an app from the Flask constructor (ignore the "__name__" for our purposes)
    app = Flask(__name__)

    # For "/hello/world" requests, run the hello function
    @app.route("/hello/world")
    def hello():
        return "Hello World!"

    # When this file is executed, start the server by listening on the default port
    if __name__ == "__main__":
        app.run()

Go ahead and copy and paste this text into a text editor and save it in a file called hello_world.py. Then run $ python hello_world.py and check the browser (or telnet) for the results.

HTML Templates

One last thing: HTML templates may seem kind of dumb at first. However, when compared with the alternative – concatenating HTML strings by hand – HTML templates are heavenly.

How your grandfather generated HTML:

Exercise 17:

function(name, photo) {
    return '<html> <head> </head> <body> <h1> Hello' + name + '. </h1>' +
           '<img src="' + photo['src'] + '"></img> </body> </html>'
}

This is how one would write it Flask's Jinja with an arbitrary number of photos:

Exercise 18:

<html>
 <head>
 </head>
    <body>
        <h1> Hello {{ name }} </h1>
        
        {% for photo in photos %}
            <img src={{ photo['src'] }}> </img>
        {% endfor % }
            
    </body>
</html>

It should be clear that the above file is not HTML. If you saved this into a .html file and statically hosted it, the template would not render and it'd probably trigger a syntax error. But this isn't how templates work. Instead, what happens behind the scenes is that Flask pareses out where the variables needed to be added, and then uses the appropriate values (in context) to fill in those gaps. Basically it does exactly what I did above manually, but automatically.

Cheat sheet for Jinja: {{ variable_expression }} returns the value of the given expression, while {% flow_control %} controls the logical flow of the HTML generation. When in doubt, check the documentation. There are way too many templating languages out there to clutter one's brain by memorizing any given one of them.

Git and Github

Exercise 19:

Almost forgot: git! Go ahead and follow the instructions to download and install git.

Git is simple:

  • When you want to tell git to keep track of a given document's subsequent changes:

$ git add

  • When you want to tell git to save a particular state in the tracked (or add-ed) documents: $ git commit -m "saving my current state"

  • And when you want to push the current (or commit-ed) state in git up to the Github server: $ git push

We know that God loves programmers, for had he not, he would not have invented the feeling one gets when push-ing code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment