In my SF2 project I have an entity (Category) which I am representing in a hierarchical format with a parent at the top, followed by children, grandchildren etc.
The Category entity has a getChildren method, which works and returns Category entity objects.
I'm trying to work out a way to make this layout more dynamic, rather than having to explicitly set children and grandchildren variables within the template.
Is there a better way to do this?
<ul class="sortable">
{% for cat in cats %}
{% set children = cat.getChildren %}
<li id="menuItem_{{ cat.id }}">
<div data-id="{{ cat.id }}">
<span>{{ cat.name }}</span>
</div>
{% for child in children %}
{% set grandchildren = child.getChildren %}
<ul>
<li id="menuItem_{{ child.id }}">
<div data-id="{{ child.id }}">
{{ child.name }}
</div>
{% for grandchild in grandchildren %}
<ul>
<li id="menuItem_{{ grandchild.id }}">
<div data-id="{{ grandchild.id }}">
{{ grandchild.name }}
</div>
</li>
</ul>
{% endfor %}
</li>
</ul>
{% endfor %}
</li>
{% endfor %}
</ul>
so what you are trying to achieve is recursive parsing of a tree in twig right?
If so, have a look at macros
.
{% import _self as macros %}
{% macro showChild(object) %}
{% import _self as macros %}
<ul>
{% for child in object.children %}
{{ macros.showChild(child) }}
{% endfor %}
<li id="menuItem_{{ object.id }}">
<div data-id="{{ object.id }}">
{{ object.name }}
</div>
</li>
</ul>
{% endmacro %}
<ul class="sortable">
{% for cat in cats %}
{{ macros.showChild(cat) }}
{% endfor %}
</ul>
that's all :)
let me know if you need help
EDIT 1:
If you want to use the macro in another file, remove the "import _self" line and just import it with an alias in another file:
index.html.twig:
{% import 'macro_file_name.html.twig' as macros %}
then you can use the same notation to call it
Related
In symfony 4.1
In the controler:
$this->addFlash(
'notice',
'Your changes were saved!'
);
return $this->render(...);
Twig base template:
{% for message in app.flashes('notice') %}
<div class="flash-notice">
{{ message }}
</div>
{% endfor %}
That works fine, but I want to wrap ALL messages in a div. The below does not work:
{% if app.flashes is not empty %}
<div id="messageBox" class="overlay">
<div class="message" onclick="slide(document.querySelector('#messageBox')); this.classList.add('fadeAway');">
{% for label, messages in app.flashes %}
<section class="{{ label }}">
<p><b>{{ label }}</b></p>
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</section>
{% endfor %}
</div>
</div>
{% endif %}
The problem is that the line {% if app.flashes is not empty %} erases the messages, so the following for loops and empty result.
How do I use peekAll() for the if logic?
The correct way to check with peekAll() is {% if app.session.flashbag.peekAll() is not empty %} This will not clear the flashBag as per documentation.
I do not know if this is the best way to do this, but the following is my solution.
In the base.html.twig:
{% set flashes = app.flashes %}
{% if flashes is not empty %}
<div id="messageBox" class="overlay">
<div class="message" onclick="slide(document.querySelector('#messageBox')); this.classList.add('fadeAway');">
{% for label, messages in flashes %}
<section class="{{ label }}">
<p><b>{{ label }}</b></p>
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</section>
{% endfor %}
</div>
</div>
{% endif %}
Basically, set the returned value of app.flashes to flashes and handle that.
I'm not familiar with timber at all, but am helping a friend finish up a project that was built with it. So any help would go a long way please!
I have only the first two tiers showing up. Is there a way to call on the child of a child?
I'm using the code here, and added to it another tier under child https://timber.github.io/docs/guides/menus/
{% if menu %}
<div class="header-menu-items">
<div class="header-menu-item mod-title">
<a href="{{ site.url }}" class="" rel="home">
<div class="header-item-logo">
<div class="sitelogo">{{ site.name }}</div>
</div>
</a>
</div>
{% for item in menu.get_items() %}
<div class="header-menu-item {{ item.current ? 'is-active' : '' }}">
<div class="header-menu-item-link">
<a target="{{ item.target }}" href="{{ item.link }}">{{ item.title }}</a>
</div>
<div class="header-menu-item-triangle"></div>
<div class="header-menu-item-mega {{ item.section_colour ? " mod-#{item.section_colour}" : '' }}">
{% if item.master_object.thumbnail %}
<div class="mega-image mod-image" style="background-image: url( {{item.master_object.thumbnail.src('thumbnail') }} )">
{% else %}
<div class="mega-image">
{% endif %}
{{ item.title }}
</div>
<div class="mega-items">
{% for child in item.children %}
<div class="mega-item">
<a target="{{ child.target }}" href="{{ child.link }}">
<span class="mega-item-title">{{ child.title }}<br /></span>
<span class="mega-item-excerpt">Mega menu description lorem ipsum dolores</span>
</a>
</div>
{% for child in child.children %}
Just testing to see if it'll even show up first before applying style<br />
{{ child.title }}<br />
{% endfor %}
{% endfor %}
</div>
</div>
</div>
{% endfor %}
</div>
{% endif %}
You can access menus several layers deep by nesting for loops inside of one another. Here is a code snippet that I have tested and works.
{% for item in menu__main.items %} {# This is the top level #}
<p>{{ item }}</p>
{% if item.children %}
{% for child in item.children %} {# 2nd Level #}
<p><em>{{ child }}</em></p>
{% if child.children %}
{% for third in child.children %} {# 3rd Level #}
<p><strong>{{ third }}</strong></p>
{% endfor %} {# for third in child.children #}
{% endif %} {# if child.children #}
{% endfor %} {# for child in item.children #}
{% endif %} {# if item.children #}
{% endfor %} {# for item in menu__main.items #}
I have added comments to the end of the lines to hopefully make this more clear. So at the top, you are looping through item in menu__main.items
Then to get the children inside of these, you loop through item.children since item is the variable that represents each nav item at the top/main level. You loop through item.children to get to the next level or the children inside of the main/top level.
Then to get inside of the third level, you loop through child.children since child is the variable that represents the 2nd level. We want to loop through the children of this 2nd level. so we do third in child.children. third is the variable that represents the items 3 levels down.
I hope you can see the pattern here and you can continue this even further if you have items at even deeper levels, although at some point it will probably get ridiculous. Like if you have items nested 5 or 6 levels deep.
Let me know if that makes sense and if not I will be more than happy to try and explain it another way if you still have questions.
Cheers
I recently implemented a blog that takes content from two post types and displays them in a tabbed navigation. The problem I encounter is that I can't seem to be able to create pagination links for each post type without one overriding the other.
<div id="view1">
{% block content %} {% for post in posts %} {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %} {% endfor %} {% endblock %}
<div class="tool-pagination">
<ul class="pages">
<li>
{% if pagination.prev %}
Prev
{% endif %}
</li>
{% for page in pagination.pages %}
<li>
{% if page.link %}
{{page.title}}
{% else %}
<span class="{{page.class}}">{{page.title}}</span>
{% endif %}
</li>
{% endfor %}
<li>Next
</li>
</ul>
{% if pagination.next %} {% endif %}
</div>
</div>
<!-- Workbench Tab -->
<div id="view2">
{% block workbench %} {% for post in workbench %} {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %} {% endfor %} {% endblock %}
<div class="tool-pagination">
<ul class="pages">
<li>
{% if pagination.prev %}
Prev
{% endif %}
</li>
{% for page in pagination.pages %}
<li>
{% if page.link %}
{{page.title}}
{% else %}
<span class="{{page.class}}">{{page.title}}</span>
{% endif %}
</li>
{% endfor %}
<li>Next
</li>
</ul>
{% if pagination.next %} {% endif %}
</div>
</div>
My index.php file looks like this:
$context['pagination'] = Timber::get_pagination();
I tried following the instructions on the timber site pagination but all I've managed to do is choose which category is paginated not both
Thanks in advance!!
Ivan
Multiple pagination wasn't something I really anticipated for. But here's how I think it could work:
$context['posts'] = Timber::get_posts();
$context['posts_pagination'] = Timber::get_pagination();
$query = array('post_type' => 'workbench');
$context['workbench'] = Timber::get_posts($query);
query_posts($query); //this forces WP to rerun query stuff
$context['workbench_pagination'] = Timber::get_pagination();
This is not tested, but based on what you got, this is the closest stab I can take
My menu needs some work. I need to have a class on the parent menu items, but with my recursion, it is not working.
This is (part of) my menu:
Home
Teachers (id teachers)
Contact
Info
Projects
myproject
yourproject
I start with "teachers" like this:
{% show_menu_below_id "teqchers" 0 1 0 1 "teachers_menu.html" %}
And this is my teachers_menu.html:
{% load menu_tags %}
{% for child in children %}
<li class="{% if child.selected %}selected parent_{{forloop.counter}}{% endif %} {% if child.sibling %}parent_{{forloop.counter}} {% endif %}">
{{ child.get_menu_title }}
{% if child.children %}
<div class="submenu">
<ul>
{% show_menu from_level to_level extra_inactive extra_active template "" "" child %}
</ul>
</div>
{% endif %}
</li>
{% endfor %}
With this in place, my menu is working for a bit.
When i click Projects, all is well and the 2 projects are in view. But when i click a project, i expect the page to show, but it does not, it does rebuild my menu, and adds the needed class to the child elements:
{% if child.selected %}selected parent_{{forloop.counter}}{% endif %}
Obvious because it is a child now i guess, but how to prevent this? I only need that class for the first menu items.
Instead of doing this:
{% show_menu from_level to_level extra_inactive extra_active template "" "" child %}
I now added another template like this:
{% show_menu from_level to_level extra_inactive extra_active "teachers_submenu.html" "" "" child %}
And in that template I now have:
{% load menu_tags %}
{% for child in children %}
<li class="{% if child.selected %}selected{% endif %}">
{{ child.get_menu_title }}
</li>
{% endfor %}
So the extra template takes care of the submenu. With some styling it now works.
Im kinda new to Django CMS and im trying my best to avoid asking, but this one drives me crazy.
I made a Wiki app with a Topic, and Category model. I hooked it to a Site on my CMS and added it to my Menu. Now i would like to be able to show all Top-Level categories, their Child Categories & Topics, and the Child categories of these, and so on, on my menu.
Menu/Navigation should look like this:
Wiki
Category1
Category1.1
Topic
Category1.2
Topic
Category2
Topic
Category3
...
Right now i can only show the Top categories:
Wiki
Category1
Category2
Category3
I Already created a menu.py to get a Custom SubMenu on my Wiki (the one you see above):
menu.py
class WikiSubMenu(CMSAttachMenu):
name = _("Wiki Sub-Menu")
def get_nodes(self, request):
nodes = []
categories = Category.objects.filter(parent_id__isnull=True)
for c in categories:
node = NavigationNode(
mark_safe(c.name),
c.get_absolute_url(),
c.id,
)
nodes.append(node)
return nodes
menu_pool.register_menu(WikiSubMenu)
My Category Model:
class Category(models.Model):
''' Category model. '''
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True)
parent = models.ForeignKey(
'self',
null=True,
blank=True,
related_name='children'
)
sort = models.IntegerField(default=0)
class Meta:
ordering = ['sort', 'name']
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('topics:categories_category_detail', (), {'slug': self.slug})
def get_all_children(self):
return Category.objects.filter(parent=self)
Now, is it possible to create a Sub-SubMenu, for all Categories with Childs, and their Childs, and their Childs, and so on?
Thanks for help & sorry for bad english
-- EDIT : --
I just found that:
docs.django-cms.org/en/3.0.6/extending_cms/app_integration.html#integration-modifiers
(Removed direct link to add 2 new Links, sorry for that)
I think that is what im looking for, i was kinda blind that i didn't found it. I'll try it out and Post the Answer if it worked out.
-- EDIT (AGAIN): --
The modifier didn't worked for me, but i got a whole piece further,
i read the Docs again, and found that i can give the NavigationNodes an optional attr dictonary, which i filled with all Categories with parent=c, on that way i had the data i needed, then i found that real nice bootstrap dropdown menu, that does exacly what i wanted. So my code until now looks like that:
menu.py
class TopicsSubMenu(CMSAttachMenu):
name = _("Wiki Sub-Menu")
def get_nodes(self, request):
nodes = []
categories = Category.objects.filter(parent_id__isnull=True)
for c in categories:
node = NavigationNode(
mark_safe(c.name),
c.get_absolute_url(),
c.pk,
attr=dict(
subcategories=Category.objects.filter(parent=c),),
)
nodes.append(node)
return nodes
And my Template:
menu.html
{% for child in children %}
<li>
{% if child.children %}
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
{{ child.get_menu_title }}
<span class="caret">
</span>
</a>
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
{% for child in child.children %}
{% if child.attr.subcategories.count %}
<li class="dropdown-submenu">
<a tabindex="-1" href="#">{{ child.get_menu_title }}</a>
<ul class="dropdown-menu">
{% for subcategory in child.attr.subcategories %}
<li>
<a tabindex="-1" href="{{ subcategory.get_absolute_url }}">{{ subcategory }}</a>
</li>
{% endfor %}
</ul>
</li>
{% else %}
<li>{{ child.get_menu_title }}</li>
{% endif %}
{% endfor %}
</ul>
{% else %}
<a href="{{ child.get_absolute_url }}">
<span>
{{ child.get_menu_title }}
</span>
</a>
{% endif %}
</li>
{% if class and forloop.last and not forloop.parentloop %}
{% endif %}
{% endfor %}
My next step will be to write the whole "for" loops from the template in a Method, make it recursive with a while loop or something and post the result as Answer.
I hope i can help someone with that stuff :)
WOHO! I finally did it!
base.html
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
{% show_menu 0 100 100 100 "menu.html" %}
</ul>
</div>
menu.html:
{% for child in children %}
<li class="child{% if child.selected %} selected{% endif %}{% if child.ancestor %} ancestor{% endif %}{% if child.sibling %} sibling{% endif %}{% if child.descendant %} descendant{% endif %}{% if child.children %} dropdown{% endif %}">
<a {% if child.children %}class="dropdown-toggle" data-toggle="dropdown"{% endif %} href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">
<span>{{ child.get_menu_title }}</span>{% if child.children|length %}<span class="caret"></span>{% endif %}
</a>
{% if child.children %}
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
{% show_menu from_level to_level extra_inactive extra_active "dropdownmenu.html" "" "" child %}
</ul>
{% endif %}
</li>
{% if class and forloop.last and not forloop.parentloop %}{% endif %}
{% endfor %}
and my dropdownmenu.html:
(The recursive stuff starts here)
{% load i18n menu_tags cache mptt_tags %}
{% for child in children %}
<li {% if child.children %}class="dropdown-submenu"{% else %} {% endif %}>
<a tabindex="-1" href="{{ child.attr.redirect_url|default:child.get_absolute_url }}">{{ child.get_menu_title }}</a>
{% if child.children %}
<ul class="dropdown-menu">
{% show_menu from_level to_level extra_inactive extra_active "dropdownmenu.html" "" "" child %}
</ul>
{% endif %}
</li>
{% endfor %}
and the most important, menu.py:
class TopicsSubMenu(CMSAttachMenu):
name = _("Wiki Sub-Menu")
def get_nodes(self, request):
nodes = []
categories = Category.objects.all()
for c in categories:
node = NavigationNode(
mark_safe(c.name),
c.get_absolute_url(),
c.pk
)
if c.parent:
node.parent_id = c.parent_id
nodes.append(node)
topics = Topic.objects.all().exclude(category__isnull=True)
for t in topics:
node = NavigationNode(
mark_safe(t.title),
t.get_absolute_url(),
t.pk,
t.category.all()[0].id,
parent_namespace="TopicsSubMenu"
)
nodes.append(node)
return nodes
menu_pool.register_menu(TopicsSubMenu)
And thats it!