Yes it probably easiest to define your own render_template
function:
def render_template_form(template, **kwargs):
quicksearch = QuickSearchForm()
return render_template(template, quicksearch=quicksearch, **kwargs)
Then just replace in your own functions:
@bp.route('/')
def home():
return render_template_form('index.html')
I am trying to implement a WTForms search feature on every page of my Flask website. I would like avoid creating the form for every Python function.
At the moment, I generate the QuickSearchForm()
for every function and pass it into every page. However, I would much rather define it once and have it load onto every webpage automatically.
Is this possible with WTForms?
Here is a snippet of the current Python code:
...
class QuickSearchForm(FlaskForm):
name = StringField(
render_kw={"placeholder": "Quick Search"}
)
...
@bp.route('/')
def home():
quicksearch = QuickSearchForm()
return render_template('index.html', quicksearch=quicksearch)
@bp.route('/content')
def content():
quicksearch = QuickSearchForm()
return render_template('content.html', quicksearch=quicksearch)
@bp.route('/quick_search', methods=('GET', 'POST'))
def quick_search():
quicksearch = QuickSearchForm()
if request.method == 'POST':
return render_template('results.html', results=results, quicksearch=quicksearch)
return render_template('home.html', quicksearch=quicksearch)
And the HTML for the form:
<form method="POST" action="{{ url_for('home.quick_search') }}">
<fieldset class="form-field">
{{ quicksearch.name }}
{% if quicksearch.name.errors %}
<ul class="errors">
{% for error in quicksearch.name.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</fieldset>
{{ quicksearch.hidden_tag() }}
</form>
I would rather define the quicksearch
in the __init__
and be done.