Created
September 19, 2012 18:28
-
-
Save gbaldera/3751301 to your computer and use it in GitHub Desktop.
Macro para generar dropdowns en Jinja2 (usando Flask)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'gbaldera' | |
from flask import Flask, request, g, redirect, url_for, abort, render_template | |
app = Flask(__name__) | |
app.config.from_object(__name__) | |
@app.route('/', methods=['GET', 'POST']) | |
def usuarios(): | |
#resultado de SELECT id, nombre FROM usuarios ORDER BY nombre | |
res = [{'id': 1, 'nombre': 'Fulano'}, {'id': 2, 'nombre': 'Fulanito'}] | |
usuarios = [(di['id'], di['nombre']) for di in res] | |
return render_template('usuarios.html', usuarios=usuarios) | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% macro dropdown(name, data, selected = [], extra = '') -%} | |
<select name="{{ name }}" {{ extra|safe }}> | |
{%- for ind, val in data %} | |
<option value="{{ ind }}" {% if ind in selected %}selected="selected"{% endif %}>{{ val }}</option> | |
{%- endfor %} | |
</select> | |
{%- endmacro %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="widget-content"> | |
{% from "macros/dropdown.html" import dropdown %} | |
<form action="{{ request.base_url }}" method="post" accept-charset="utf-8"> | |
{{ dropdown('usuario', usuarios, extra='id="usuarios_select"') }} | |
<button type="submit" class="btn btn-secondary">Buscar</button> | |
</form> | |
</div> | |
Excelente Edgar. Que bueno que te es útil
No puedo creer que esta publicación tenga 8 años, me ha servido el código, muchísimas gracias!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excelente! se que lleva mucho tiempo que lo publicaste, pero estoy empezando mi mundo con flask y llevo días buscando algo similar, mil gracias!