mixxorz / slippers

A UI component framework for Django. Built on top of Django Template Language.

Home Page:https://mitchel.me/slippers/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Can I use a single fragment in multiple blocks?

AaronPresley opened this issue · comments

Firstly, thank you for your work on Slippers!

I've looked through the documentation and can't find something directly answering this question.

Assume I have a base template similar to the following:

// base.html
<div class="mobile-menu">{% block menu_mobile %}{% endblock %}</div>
<div class="wrapper">
  <div class="desktop-menu">{% block menu_desktop %}{% endblock %}</div>
  <div class="content">{% block content %}{% endblock %}</div>
</div>

Note that since blocks must have unique names, I'm enable to directly repeat that content despite wanting the exact same markup.

I would LOVE to be able to use fragments outside of a block, like so:

// some-page.html
{% extends 'base.html' %}
{% fragment as menu %}
  <ul>
    <li><a href="#">My DRY Menu</a></li>
  </ul>
{% endfragment %}
{% block menu_mobile %}{{ menu }}{% endblock %}
{% block menu_desktop %}{{ menu }}{% endblock %}
{% block content %}
  My content here 
{% endblock %}

Unfortunately this isn't working in my experimentation. I'm guessing this is a scoping issue with block, but figured it was worth confirming whether this is possible.

Thanks for your time.

Hi @AaronPresley

I think you're right that this isn't possible, and it is an issue with block. Nothing outside of block tags is rendered when using extend.

My only suggestion would be to make a menu component instead.

{# menu.html #}
<ul>
  <li><a href="#">My DRY Menu</a></li>
</ul>
{# some-page.html #}
{% extends 'base.html' %}

{% block menu_mobile %}{% menu %}{% endblock %}
{% block menu_desktop %}{% menu %}{% endblock %}
{% block content %}
  My content here 
{% endblock %}

Thanks for verifying, @mixxorz