Updated Large app how to (markdown)

debrice 2012-02-04 11:56:52 -08:00
parent 9c94062572
commit 266ee5989a

@ -233,12 +233,68 @@ The view is where we'll declare our Blueprint. Using url_prefix will prefix ever
## First template
Jinja is integrated within Flask. One of the great feature of Jinja is the inheritance and the logic available (conditional structure, loop, context modification...). We'll create a `base.html` template from which we'll inherit from on each of our template. You can even have more than 1 inheritance (like having your template inheriting from twocolumn.html template which itself inherit from main.html)
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
{% block css %}
<link rel="stylesheet" href="/static/css/reset-min.css" />
<link rel="stylesheet" href="/static/css/main.css" />
{% endblock %}
{% block script %}
<script src="src="/static/js/main.js" type="text/javascript"></script>
{% endblock %}
</head>
<body>
<div id="header>{% block header %}{% endblock%}</div>
<div id="content>{% block content %}{% endblock%}</div>
<div id="footer>{% block footer %}{% endblock%}</div>
</body>
</html>
Now we won't have to redefine our html structure anymore, and any modification done on `base.py` will be visible on all your child templates. Here is the `/app/templates/users/register.html` template (It's a good habit to use the view name to for the template file name).
{% extends "base.html" %}
{% block content %}
{% from "forms/macros.html" import render_field %}
<form method="POST" action="." class="form">
{{ form.csrf }}
{{ render_field(form.name, class="input text") }}
{{ render_field(form.email, class="input text") }}
{{ render_field(form.password, class="input text") }}
{{ render_field(form.confirm, class="input text") }}
{{ render_field(form.accept_tos, class="input checkbox") }}
<label>Repcaptcha</label>
{{ form.repcaptcha }}
<input type="submit" value="Register" class="button green">
</form>
<a href="{{ url_for('restaurant.register') }}">Register a restaurant</a>
{% endblock %}
This template will use a macro to automate the construction of html fields. This macro will be stored in `/app/forms/macros.html` (since this macro will be called in different module, we'll store it in a separated file).
{% macro render_field(field) %}
<div class="form_field">
{{ field.label(class="label") }}
{% if field.errors %}
{% set css_class = 'has_error ' + kwargs.pop('class', '') %}
{{ field(class=css_class, **kwargs) }}
<ul class="errors">{% for error in field.errors %}<li>{{ error|e }}</li>{% endfor %}</ul>
{% else %}
{{ field(**kwargs) }}
{% endif %}
</div>
{% endmacro %}
## Settings up the app
Here is the `/app/__init__.py`
from flask import Flask, render_template
from flask import Flask, render_template
from flaskext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
@ -253,3 +309,4 @@ Here is the `/app/__init__.py`
from app.users.views import mod as usersModule
app.register_blueprint(usersModule)