In Wagtail streamfield template how to check if a field of a structblock inside a structblock is null? - wagtail

I have a StructBlock like this :
class CardBlock(blocks.StructBlock):
header= blocks.StructBlock([
("text", blocks.CharBlock(required=False, help_text="Header text")),
("classes", blocks.CharBlock(required=False, help_text="Header css classes")),
],
template="streams/card_header_block.html")
image= ImageChooserBlock(required=False)
icon= blocks.CharBlock(required=False, help_text="fontawesome classes for an icon")
title= blocks.StructBlock([
("text", blocks.CharBlock(required=False, help_text="Title text")),
("classes", blocks.CharBlock(required=False, help_text="Title css classes")),
],
template="streams/card_title_block.html")
bodyHTML = blocks.RawHTMLBlock()
footer= blocks.StructBlock([
("text", blocks.CharBlock(required=False, help_text="Footer text")),
("classes", blocks.CharBlock(required=False, help_text="Footer css classes")),
],
template="streams/card_footer_block.html")
class Meta:
template = "streams/card_block.html"
icon = "placeholder"
label = "Card"
And a template like this:
{% load wagtailcore_tags %}
{% load wagtailimages_tags %}
{% image value.image fill-300x150 as img %}
<div class="card {% if value.classes %} {{value.classes}} {% endif %}">
{% if value.header.text is not Null %}
{% include_block value.header %}
{% endif %}
{% if value.image %}
<img src="{{ img.url }}" alt="{{ img.alt}}" class="card-img-top" />
{% endif %}
<div class="card-body">
{% if value.title %}
{% include_block value.title%}
{% endif %}
{% if value.subtitle %}
{% include_block value.subtitle%}
{% endif %}
<div class="card-text">{% include_block value.bodyHTML %}</div>
{% if value.link %}
{% include_block value.link%}
{% endif %}
</div>
{% if value.footer %}
{% include_block value.footer%}
{% endif%}
</div>
I am trying to check is a child block like Header has its value filled by the page editor or not. If not I do not show the HTML. But I am afraid the header div still shows up. Someting is wrong with the way I am putting the condition.

A blank CharBlock is equal to the empty string, which is not the same as null (and in any case, Python's null value is None, not Null). You can test this the same way that you've tested other empty values in your template: {% if value.header.text %}

Related

CRAFT CMS 3 loop matrix field - variable entry does not exist

I'm trying to loop a matrix field that has one block containing 3 items.
{% for block in entry.galeria.type('itemsGaleria') %}
{% if block.titulo|length %}
{{ block.titulo.first }}
{% endif %}
{% endfor %}
But craft always throws the error variable entry does not exist.
I read the matrix section from craft 3 docs but cannot fix this problem.
Any clues?
Well, as there where no sugestions, and i never give up, i figured out for myself :)
Here it is:
{% set entries = craft.entries.section("galeria").all() %}
{% for entry in entries %}
{% for block in entry.galeriaMatrix.all() %}
{% switch block.type %}
{% case "itemsGaleria" %}
{% for image in block.fotografia %}
<img src="{{image.url}}" alt="{{image.title}}" />
{% endfor %}
{{ block.titulo }}
{{ block.texto }}
{% default %}
{% endswitch %}
{% endfor %}
{% endfor %}
It does what i need, which is loop all the entrances in the matrix block field.

Wagtail Show latest blog posts on Homepage through a streamfield

I have 3 mains sections in my site, homepage, blog index, and blog specific. I am using the streamfield function in wagtail to order various sections in the homepage. One of those sections is for the latest three blog posts.
I have done this for the blog index page, but can't grab the latest blog posts in the streamfield.
My model looks like this
class CaseStudiesIndex(Page):
def casestudies(pages):
casestudies = CaseStudyPage.objects.all().order_by('-first_published_at')
return casestudies
intro = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('intro', classname="full")
]
class LatestPosts(blocks.StructBlock):
static = blocks.StaticBlock(admin_text='Latest posts: no configuration needed.',)
def casestudies(pages):
casestudies = CaseStudyPage.objects.all().order_by('-first_published_at')[:3]
return casestudies
class Meta:
icon = 'doc-full'
label = 'Latest Posts'
template = 'blocks/_latestPosts.html'
class HomePage(Page):
blocksbody = StreamField([
('lead_banner', LeadBanner()),
('latest_posts', LatestPosts()),
('team', Team())
],null=True,blank=True)
content_panels = Page.content_panels + [
StreamFieldPanel('blocksbody'),
]
In my block folder I am calling the file fine and it renders the wrapper fine but I can't grab any of the data, I have tried a bunch of ways but nothing returns.
{% load wagtailcore_tags wagtailimages_tags %}
{% load static %}
<section>
<div class="wrapper__inner">
<ul>
{% for case in self.casestudies %}
{{case.title}}
{% endfor %}
{% for case in self.case_studies %}
{{case.title}}
{% endfor %}
{% for case in self.latest_posts %}
{{case.title}}
{% endfor %}
{% for case in page.casestudies %}
{{case.title}}
{% endfor %}
{% for case in page.case_studies %}
{{case.title}}
{% endfor %}
{% for case in page.latest_posts %}
{{case.title}}
{% endfor %}
</ul>
</div>
</section>
For the Blog Index page that does work I do the following.
{% extends "inner_base.html" %}
{% load wagtailcore_tags %}
{% block body_class %}template-case-studies{% endblock %}
{% block content %}
<section>
<div class="wrapper__inner">
<h1>{{self.title}}</h1>
<ul>
{% include "blocks/CaseStudiesLatestBlock.html" %}
</ul>
</div>
</section>
{% endblock %}
And the CaseStudiesLatestBlock.html which works fine looks like
{% load wagtailcore_tags wagtailimages_tags %}
{% load static %}
{% for case in self.casestudies %}
<li>
<strong>{{ case.title }}</strong>
</li>
{% endfor %}
Defining your own methods on a StructBlock won't work - the self (or value) variable you receive on the template is just a plain dict, not the StructBlock object itself. (This might seem counter-intuitive, but it's consistent with how blocks work in general: just as a CharBlock gives you a string value to work with and not a CharBlock instance, StructBlock gives you a dict rather than a StructBlock instance.)
Instead, you can define a get_context method (as documented here) to provide additional variables to the template:
class LatestPosts(blocks.StructBlock):
static = blocks.StaticBlock(admin_text='Latest posts: no configuration needed.',)
def get_context(self, value, parent_context=None):
context = super(LatestPosts, self).get_context(value, parent_context=parent_context)
context['casestudies'] = CaseStudyPage.objects.all().order_by('-first_published_at')[:3]
return context
You can then access the casestudies variable in the template, e.g. {% for case in casestudies %}.

Twig check if value is in array

I'm having trouble to check if a value is present in an array with Twig.
I want to hide a shipping method in a checkout if there's a certain product in the cart.
I can only use Twig code so I have to find a logic in that.
So let's say when product ID 1234 is in cart then I want to hide #certain_div
So what I have is this ->
{% if checkout %}
{% set array = theme.sku_shipping_rule | split(',') %}
// theme.sku_shipping_rule = a text string like 1234, 4321, 5478
{% if checkout.products %}
{% for product in checkout.products %}
{% if product.sku in array %}
<style>
#certain_div {
display: none;
}
</style>
{% endif %}
{% endfor %}
{% endif %}
{% endif %}
The problem I'm facing is that it seems my code always returns true. So even if the product.sku doens't match a value in the array it still hides #certain_div. I've tested that with placing {{ product.sku }} just before <style>.
What do I wrong?
Any help greatly appreciated!
UPDATE:
I've updated the question/code to show what's happening
{% if checkout %}
{% set skuToCheck = theme.sku_shipping_rule | split(',') %}
{% set skuInCart = [] %}
{% if checkout.quote.products %}
{% for product in checkout.quote.products %}
{% set skuInCart = skuInCart | merge([product.sku]) %}
{% endfor %}
{% endif %}
{% for myVar in skuInCart %}
{{ myVar }}<br/>
{% endfor %}
// this prints
PSYGA1 // where this sku should NOT match
FP32MA4
{% for myVar in skuToCheck %}
{{ myVar }}<br/>
// this prints
FP32LY4
FP32STR4
FP32MA4
{% if myVar in skuInCart %} // also tried with | keys filter
{{ myVar }} is found
{% endif %}
{% endfor %}
{% endif %}
So what I did is placing the sku's from the products which are in the cart in an array skuInCart. Next I want to check if myVar is present in the skuInCart array. If so print myVar is found.
What happens is that you should expect that it prints only the matching results. However it actually prints all values present skuInCart (using keys filter) or completely blank without using keys filter.
What you are doing in theory should work, have a look a this fiddle example to show you a working demonstration:
https://twigfiddle.com/yvpbac
Basically:
<div id="certain_div">
This should not show up
</div>
{% set searchForSku = "890" %}
{% set productSkuArrayString = "1234,4567,890" %}
{% set productSkuArray = productSkuArrayString|split(',') %}
{% if searchForSku in productSkuArray %}
<style>
#certain_div {
display: none;
}
</style>
{% endif %}
<!-- New Trial -->
<div id="certain_div">
This should show up
</div>
{% set searchForSku = "891" %}
{% set productSkuArrayString = "1234,4567,890" %}
{% set productSkuArray = productSkuArrayString|split(',') %}
{% if searchForSku in productSkuArray %}
<style>
#certain_div {
display: none;
}
</style>
{% endif %}
Will result in:
<div id="certain_div">
This should not show up
</div>
<style>
#certain_div {
display: none;
}
</style>
<!-- New Trial -->
<div id="certain_div">
This should show up
</div>
You can use iterable to check if a variable is an array or a traversable object:
{% if items is iterable %}
{# stuff #}
{% endif %}

Liquid (Shopify) scope questions

I'm trying to set two variables outside of a few nested loops (for loops) and then check or reassign the variables inside the for. Basically, I'm trying to check for current_tags and display links to any tags under those tags (in the hierarchy I've got). Shopify seems to only support one level of hierarchy (collections and their associated products), but I'm trying to use these tags to make it look like I've got multiple levels of ways of classifying products. So shirt, then red shirt/brown shirt, then red silk shirt/brown silk shirt, as a shitty example.
Here's some code:
{% assign showtag = false %}
{% for link in linklists[settings.main_linklist].links %}
{% if linklists[link.handle] == empty %}
{% else %}
{% for link in linklists[link.handle].links %}
{% if linklists[link.handle] == empty %}
{% else %}
{% for link in linklists[link.handle].links %}
{% if linklists[link.handle] == empty %}
{% else %}
{% capture temp_tag %}{{current_tags.first | replace: '-', ' '}}{% endcapture %}
link {{link.title}}<br>
temp {{temp_tag}}<br>
{% if showtag == true %}
<li>{{ tag | highlight_active_tag | link_to_tag: tag }}</li>
{% endif %}
{% if link.title == temp_tag}
{% assign showtag = true %}
{% endif %}
{% endif %}
{% for link in linklists[link.handle].links %}
{% capture temp_tag %}{{current_tags.first | replace: '-', ' '}}{% endcapture %}
{% if linklists[link.handle] == empty %}
{% if showtag == true %}
<li>{{ tag | highlight_active_tag | link_to_tag: tag }}</li>
{% endif %}
{% if link.title == temp_tag %}
{% assign showtag = true %}
{% endif %}
{% else %}
{% if showtag == true %}
<li>{{ tag | highlight_active_tag | link_to_tag: tag }}</li>
{% endif %}
{% if link.title == temp_tag %}
{% assign showtag = true %}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
The above is a little messy but is properly indented on the website. Anyway, it seems like the variable showtag loses scope and cannot be found in the for loops - any solutions?

Wrong parent loop context in twig

I'm using Symfony 2.3 and Twig 1.15. I've got a nested foreach twig loop and I'm trying to get a different result for the last iteration of the outer loop.
I've seen this: http://twig.sensiolabs.org/doc/recipes.html#accessing-the-parent-context-in-nested-loops
However I'm getting a different result - an error in the line where I access the parent context:
Key "loop" for array with keys "groups, scores, type, user, assetic, app, avatarsDir, sonata_block, _parent, _seq, group, _key, subgroup" does not exist in "(...)"
the relevant code, stripped of classes, ids and unnecessary tags:
{% for group in groups %}
<div>
{% for subgroup in group.subgroups %}
{% for test in subgroup.tests %}
{% block test_block_box %}
{% if not loop.parent.loop.last %}
(html follows...)
{% else %}
(some different html follows...)
{% endif %}
{% endblock %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
I have made sure that the error does not refer to the inner loop call, i.e. I replaced loop.parent.loop.last with loop.last and the page rendered successfully (contents obviously wrong, but it didn't crash).
What am I doing wrong when accessing the parent context??
Simply remove {% block test_block_box %} and {% endblock %}, the loop parent shoud be accessible.
You can try to define a value outside of the {% block %} and see if you have access to it in the {% block %}:
{% for group in groups %}
<div>
{% for subgroup in group.subgroups %}
{% for test in subgroup.tests %}
{% set test_loop_is_last = loop.last %} {# define the value #}
{% block test_block_box %}
{% if not test_loop_is_last %}{#test the value #}
(html follows...)
{% else %}
(some different html follows...)
{% endif %}
{% endblock %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}

Resources