# Template fragment caching with nested templates

**URL:** <https://forum.djangoproject.com/t/template-fragment-caching-with-nested-templates/26187>\
**Category:** Templates & Frontend\
**Created:** [December 15, 2023, 7:33am UTC](https://forum.djangoproject.com/t/template-fragment-caching-with-nested-templates/26187 "2023-12-15T07:33:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![janedenone](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/janedenone/32/12025_2.png) [@janedenone](https://forum.djangoproject.com/u/janedenone)\
**Post date:** [December 15, 2023, 7:33am UTC](https://forum.djangoproject.com/t/template-fragment-caching-with-nested-templates/26187/1 "2023-12-15T07:33:02Z")

</div>

Hi, I am currently testing template fragment caching (s. my [earlier question](https://forum.djangoproject.com/t/django-caching-useless-with-csrf-protection/26172)). My project has a base template which caches everything except for the CSRF-protected searchbox

```auto
{% load cache %}
{% cache 900 head %}
...
{% endcache %}
# CSRF-protected searchbox comes here
{% cache 900 main requested_page.id %}
...
{% endcache %}

```

My template for search results is derived from the base template, and I struggle to configure the results template such that the main section is _not_ cached.

I tried embedding the cache template tag in a regular block

```auto
{% block mainstart %}{% cache 900 main requested_page.id %}{% endblock %}
{% block mainend %}{% endcache %}{% endblock %}

```

so I could leave that block empty in the results template, but this threw an error (expected `endcache` instead of `endblock`). Is there a way to avoid caching the main section for search results while keeping the nested template setup?

---

<div class="post-metadata">

**Author:** ![janedenone](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/janedenone/32/12025_2.png) [@janedenone](https://forum.djangoproject.com/u/janedenone)\
**Post date:** [December 15, 2023, 8:08pm UTC](https://forum.djangoproject.com/t/template-fragment-caching-with-nested-templates/26187/2 "2023-12-15T20:08:10Z")

</div>

I found the solution by nesting the `{% cache %}` tag entirely in a `{% block %}` tag:

```auto
{% block main %}
{% cache 900 main requested_page.id %}
...
{% endcache %}
{% endblock main %}

```

Performance increased by 62%.
