Skip to content

Instantly share code, notes, and snippets.

@lozadaOmr
Last active August 29, 2015 14:18
Show Gist options
  • Save lozadaOmr/364f00dd3ff4b1e3fc89 to your computer and use it in GitHub Desktop.
Save lozadaOmr/364f00dd3ff4b1e3fc89 to your computer and use it in GitHub Desktop.
some notes taken trying to learn Flask - Python

Render Templates

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
    user = {'nickname': 'Miguel'}  # fake user
    
    # Render the Template 'index.html', variables*?
    return render_template('index.html',
                           title='Home',
                           user=user)

Control Structures

`{% if ____ %}` Checks if it exist,

<html>
  <head>
    {% if title %}
    <title>{{ title }} - microblog</title>
    {% else %}
    <title>Welcome to microblog</title>
    {% endif %}
  </head>
  <body>
      <h1>Hello, {{ user.nickname }}!</h1>
  </body>
</html>

Looping

# Create a posts array
posts = [
    { 
        'author': {'nickname': 'John'}, 
        'body': 'Beautiful day in Portland!' 
    },
    { 
        'author': {'nickname': 'Susan'}, 
        'body': 'The Avengers movie was so cool!' 
    }
]

# Loop through posts in view
{% for post in posts %}
    <div><p>{{ post.author.nickname }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}

Template Inheritance

# To render a block
# similar to Laravel's @section()
{% block content %}{% endblock %}

# extend a block
# similar to Laravel's @extends('template.name')
{% extends "base.html" %}
{% block content %}
    <h1>Hi, {{ user.nickname }}!</h1>
    {% for post in posts %}
    <div><p>{{ post.author.nickname }} says: <b>{{ post.body }}</b></p></div>
    {% endfor %}
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment