How do you insert a template into another template?

前端 未结 4 892
猫巷女王i
猫巷女王i 2020-12-04 16:18

I have a very basic template (basic_template.html), and want to fill in the with data formatted using another partial template. The basic_template.html might contain severa

4条回答
  •  Happy的楠姐
    2020-12-04 17:14

    You can do this using a block. Blocks are a Django Template tag which will override sections of a template you extend. I've included an example below.

    basic_template.html

    
    {% block 'body' %}
    {% endblock %}
    
    

    template you want to include: (i.e. example.html)

    {% extends 'basic_template.html' %} 
    {% block 'body' %}
    /* HTML goes here */
    {% endblock %}
    

    views.py:

    return render_to_response(template='example.html', context, context_instance)
    

    Doing this will load basic_template.html, but replace everything inside of {% block 'body' %} {% endblock %} in basic_template.html with whatever is contained within {% block 'body' %} {% endblock %}.

    You can read more about blocks and template inheritance in the Django Docs

提交回复
热议问题