Twig handle multiple comparisons - twig

I'm struggeling to compare multiple values with Twig. I don't have access to any core code since this is for a SaaS platform similar like Shopify.
I want to compare product weights and set a variable if the comparison is true.
So I have multiple weights (in grams) like this (price behind it)
751 - 9990 $5
9990 - 19799 $10
19800 - 19849 $5
19850 - 19950 $14
29700 - 29749 $5
What is a good way to compare those weights and set a price accordingly? I thought something like this:
{% if (product.weight >= 751) or (product.weight <= 9990) %}
{% set shippingCosts = '5' %}
{% elseif (product.weight >= 9991) or (product.weight <= 19799) %}
{% set shippingCosts = '10' %}
However I have a very long list (12+) with different weights. So is there a quick way to handle this list? Otherwise it will become a long list with if/else :(

Good way is make custom Twig Extension
{% set shippingCosts = product.weight|custom_twig_extension %}

Related

How to separate the two values? Twig return sql group concat

i need a help for make the result.
my sql request :
$posts = $db->prepare('SELECT
CM.idpost,
CM.title,
CM.slug,
CM.content,
CM.cover,
CM.date,
GROUP_CONCAT(PC.id SEPARATOR ";") AS list_id,
GROUP_CONCAT(PC.cat_name SEPARATOR ";") AS list_cat_name,
GROUP_CONCAT(PC.icon SEPARATOR ";") AS list_icon,
GROUP_CONCAT(PC.bg SEPARATOR ";") AS list_bg,
GROUP_CONCAT(PC.slug_cat SEPARATOR ";") AS list_slug_cat,
U.iduser,
U.username,
U.avatar
FROM cms_posts CM
LEFT JOIN relation_posts RP ON RP.id_post = CM.idpost
LEFT JOIN cms_postcategory PC ON PC.id = RP.id_category
LEFT JOIN users U ON U.iduser = CM.author
GROUP BY CM.idpost
ORDER BY CM.date DESC LIMIT '.$paginationStart.','.$limit.'');
this is what my sql query for my table returns: Marketing;Général in Twig :
{{ post.list_cat_name }}
Picture demo
I need the result :
Marketing
Général
Thanks for help <3
So you've got a string like Marketing;Général. You need to create 2 links using the text for each as the link text.
I assume you similarly need to split the list_id for your idcategory value.
So something like this:
{% set categoryNames = post.list_cat_name | split(';') %}
{% set categoryIds = post.list_id | split(';') %}
{% for category in categoryNames %}
{{category}}
{% endfor %}
https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable
https://twig.symfony.com/doc/2.x/filters/split.html

Parametrized twig date

I need how to check if a custom date is inside a range.
The problem is that the API returns a calendar but year and month are sent separately and I can't create a date with twig.
This part of the code seems to return my variables as expected
<script>console.log("Year"+{{CurrYear| json_encode()| raw}});</script>
<script>console.log("Month: "+{{CurrMonth| json_encode()| raw}});</script>
while I can retrieve the day within the loop
<script>console.log("Day: "+{{key| json_encode()| raw}});</script>
I'm trying to create a data item so I can use the native comparisons. I know I can split the other date and compare it one by one, but I'm trying to avoid this
<script>console.log({{ annoForm."-".mesForm."-".key |date('Y-m-d')}}) ;</script>
So I can use it afterwards like
{% set auxDate = annoForm."-".mesForm."-".key |date('Y-m-d') %}
BUT, I can't seem to construct a valid date here so I could use it in:
{% datestart < auxDate and dateend > auxDate %}
{# condition met #}
{% endif %}
Main problem here was concatenating correctly the string when instantiating date():
{% set auxDate = ("#{annoForm}-#{mesForm}-#{key} " | date('Y-m-d') ) %}
I want to add a couple of issues i found while working on this.
First the importance of using date('Y-m-d') instead of "date()" because it will consider July before June (due alphabetic order).
Take nulls or open fields into account (in my case datestart is mandatory)
{% if datestart < auxDate and ( dateend is null or dateend > auxDate ) %}
Hope it helps!

Converting a String to Float in Twig

Basically, I have set a parameter called "rating" that's equal to a product.DETAILS.STAR_RATING which is a value imported from a database-driven field which happens to be a string, I want to multiply this value by 20 but since "rating" is a string I cannot multiply it.
How do I convert the string to a float value?
{% set rating = product.DETAILS.STAR_RATING %}
{{rating * 20}}
Very simple way, maybe strange but...
{% set rating = 0 + product.DETAILS.STAR_RATING %}
{{ rating * 20}}

How to use flask to check whether every folder has specific files or not and using jinja2 to show the result?

I am now trying to check whether every folder has specific files or not.
First, I create two list to store the is_file result.
folderlist[folder1,folder2], has_data[file1 ok,file2 nok,file1 ok, file2 ok]
But I don't know how to use jinja2 to deal with them.
I want the output can be like below.
folder1
file1 ok
file2 nok
folder2
file1 ok
file2 ok
And below is my code to check file.
Could you give me some advice or better solution?
def has_data():
folderlist = []
has_data = []
for root, dirs, files in walk(target_folder):
qq = list(root.split('\\'))
filefolder = qq[-1]
folderlist.append(filefolder)
file1_site = os.path.join(target_folder+'\\'+filefolder+'\\' + 'file1.txt')
file2_site = os.path.join(target_folder+'\\'+filefolder+'\\' + 'file2.txt')
if not os.path.isfile(file1_site):
has_data.append('file1.txt NOK')
else:
has_data.append('file1.txt OK')
if not os.path.isfile(file2_site):
has_data.append('file2.txt NOK')
else:
has_data.append('file2.txt OK')
del folderlist [0]
del has_data [0]
return render_template('hasdata.html',folderlist=folderlist,has_data=has_data)
I didn't solve your problem directly, don't know values of those list. But you can wrap your html output in pre tag for preformatted text and add - sign to for loop.
From jinja2 documentation:
You can also strip whitespace in templates by hand. If you add a minus sign (-) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed
So your template can look something like this to get output you need:
...
<pre>
{% for folder in folderlist -%}
{{ folder }}
{% for file in has_data -%}
{{ file }}
{% endfor %}
{% endfor %}
</pre>
...

Does Twig 'date' support localised dates?

Using this twig code in Craft CMS I'm getting the error shown below. The makers of Craft CMS tell me that the Twig 'date' does not support localized month names like "janvier 2016", but it's fine with English "January 2016".
Is this true?
My Twig:
{% set queryStartDate = date([month, year]|join(' ')) %}
Error:
DateTime::__construct(): Failed to parse time string (janvier 2016) at position 0 (j): The timezone could not be found in the database
Twig's date function is just a wrapper for PHP's DateTime class.
Instead of passing in localized month names into the method, convert them to their numeric equivalents (January/Janvier = 01, etc.) and pass them into yyyy-mm-dd format.
Something like:
{% set queryStartDate = date(year ~ '-' ~ month ~ '01') %}

Resources