How to verify day of the week to show / hide content - if-statement

I'm a bit stuck here and making it too complex in my head :-D
[SOLUTION]
DarkBee gave me the working solution, but unfortunately I can't up vote his answer. Thank you all very much for thinking with me!
[/SOLUTION]
What I'd like to achieve and the current situation
I have a page, let's say product.twig which includes a countdown timer file (i.e. countdown.twig) which loads a JS script with the actual functionality.
I want to hide the countdown timer on specific days of the week (saturday & sunday), and instead show a custom text. I could make this work in JS, but this needs to run the script, which causes unnecessary load. The most efficiƫnt way would be to verify which day of the week it is in TWIG, so everything is done by the server, by not loading the countdown page, and thus not loading the actual JS file.
Can this be done with an IF statement? IF day = saturday (or 6 / 7) text: Delivered tuesday ELSE include countdown.twig

Darkbee's solution works like a charm! Tweaked it a bit to make it even more efficient. As the countdown timer isn't needed on Saturday & Sunday, I don't need the ELSE statement. Instead I changed the IF in IF NOT ({% if "now"|date('N') not in [ 0, 7, ] %})
{% if "now"|date('N') not in [ 0, 7, ] %}
<div class="countdowner mt-3 d-flex align-items-center">
<span class="h4 mb-0">Morgen in huis?</span><span style="padding-top: 4px;" class="px-2"> Je hebt nog:</span>
<span style="background-color: #547A82; color: white; border-radius: 4px; width: 75px;" class="text-center h4 m-0 p-1 px-2 timeleft" id="countdownTimer"></span>
</div>
<script src="{{ 'countdowner.js.rain' | url_asset }}"></script>
{% endif %}
For the ones staring at the extension of countdowner.js.rain: It's Lightspeed HQ's framework which is based on TWIG / DRAFT

You can just use the date filter along with "now" to get the current date
{% if "now"|date('N') in [ 6, 7, ] %}
Delivered tuesday
{% else %}
{% include "countdown.twig" %}
{% endif %}
demo

Related

Is it possible to add days to the date in the template?

I have today's date in my template, which is in a loop. I want to add a counter to the cycle so that in the template I don't have today's date, but date + 1 day, date + 2 days, and so on.
{% for day_week_list in set_day_week %}
<div class="card mb-2">
<div class="card-header">
{{ day_week_list }} {{ day_data|date:'d.m' }}
</div>
<div class="card-body">
No, that's not possible. To add days to a date in HTML, you need to use a programming language such as JavaScript.

Nested if statements problem in legacy .liquid

I'm banging my head against the wall with this one since my syntax looks to be accurate but I'm not getting any results when trying to edit some legacy code on a Shopify storefront. For:
{% if product.metafields.custom_fields["custom_field_two"] != blank %}
<div role="button" tabindex="0" class="share-pdp__details--tab" id="customtwoTab"
onclick="displayDetails('customtwo')" aria-expanded="false" aria-controls="customtwo">
Section Main Title (This is displayed in all conditions)
{% if product.handle == 'product-one' %}- Product-specific added text {% else %}- Other product-specific added text {% endif %}
<span class="tab-mobile__arrow"
id="customtwo_arrow"><i class="fas fa-chevron-circle-right"></i></span>
</div>
I'm hoping to see the - Other product-specific added text but it's just not showing up once in my production dev environment. The - Product-specific added text is showing up, but nothing else.
Any ideas? Could something else be interfering?

How to reduce for loops in html in Django?

I tried the following for loops and if statements in django html, but it takes so long to load one page. First, here is the html:
{% for time in TIME_CHOICES %}
<tr class="bg-white border-b border-gray-400">
<td class="border-r border-gray-400 py-1 whitespace-nowrap text-sm font-medium text-gray-900">
{{time}}
</td>
{% for each_date in dates_in_month %}
{% if each_date not in weekends %}
{% for class in classes %}
<h1>class</h1>
{% endfor %}
{% else %}
<td class="py-1 whitespace-nowrap text-sm text-gray-500">
<ul class="list-none" style="font-size: 0.70rem; line-height: 0.85rem;">
<li>-----</li>
<li>--(--)</li>
</ul>
</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
I think this is because I have too many for loops and if statements happening in my html. Is there anyway I can increase the speed? Or is there any way I can do the same thing in django views(I am using generic list view, so I need some code for the get_context_data)? Thank you, and please leave any questions you might have.
It is always better to reduce database hits. In your code you are hitting database in an iteration so if the loop run for 1000 times it will hit database 1000 times this can be reduced to just one query like this:
classes = Class.objects.filter(
teacher=teacher, date__in=[each_date for each_date in dates_in_month
if each_date not in weekends]
).order_by('date','time')
then you can iterate the classes queryset to continue with the rest of the code.
Also make your code more readable right now it is a messy.
It's hard to say where is a performance problem in your code. Loops in html shouldn't take a lot of time. Maybe you have a lot of db queries or run some heavy methods.
Try to investigate what part of your code is really slow. You can you Silk profiler for this
Silk is a live profiling and inspection tool for the Django framework. Silk intercepts and stores HTTP requests and database queries before presenting them in a user interface for further inspection:
Installation
pip install django-silk
In settings.py add the following:
MIDDLEWARE = [
...
'silk.middleware.SilkyMiddleware',
...
]
INSTALLED_APPS = (
...
'silk'
)
Try to find the method that takes the most part of time and optimize it. Also, you can add Silk's result to your question. It helps to figure out the problem

How to make buttons change variables passed into my jinja template from my views.py?

I am trying to create a weekly plan and I want the left and right arrows to change the week. I am having trouble thinking of how to do this with Flask, Jinja, and WTForms.
My page will look something like this
Eventually I want each day to populate with any stuff the user has added to that particular day so I need the button id and value fields to have the date which I have working.
What I am having issues with is I can't figure out how to have the left and right buttons update the starting date that I am using to create these weekday cards.
The bandaid I have to even have this working as is, is I create an array starting with datetime.datetime.now() for the current week using a simple for loop. I then pass that week array into the template context as a meal variable.
views.py
...
#weeklyplan.route('')
def weeklyplans():
modalForm = ModalForm()
week = []
for i in range(6):
week.append(datetime.datetime.now() + datetime.timedelta(days=i))
return render_template('/weeklyplan/weeklyplan.html', title='Weekly Planner', form=modalForm, week=week)
Then in the weeklyplan.html jinja2 template I loop through the week array to create the cards.
weeklyplan.html
...
<button><i class="fas fa-angle-left"></i></button>
<div class="card-group">
{% for day in week %}
<div class="card">
<div class="card-header text-center">
<!-- I need to get today + 6 days from DB and allow the moving left
and right when the arrows are clicked -->
{{ day.strftime("%m/%d") }}<br>
{{ day.strftime("%A") }}
</div>
<div class="card-body text-center">
<button
id="add_{{ day.strftime('%d%m%y') }}_btn"
value="{{ day.strftime('%d%m%y') }}"
class='add-btn btn btn-primary btn-md'
data-toggle="modal"
data-target="#exampleModal"><i class="fas fa-plus-circle"></i> Add
</button>
</div>
</div>
{% endfor %}
</div>
<button><i class="fas fa-angle-right"></i></button>
...
I have been trying to figure out a way to get the buttons to the left and right (top and bottom of the code snippet). I know the way I currently do it has to go, it's a placeholder more or less.
I don't want to just redirect back to this same page with a new start date of the current start date - 7 days. I want to avoid reloading the page.
If I can find a way to have the buttons adjust the week array or loop differently such that all I need is a start date in jinja which would always be today and I can just more that by + or - 7 increments that would be ideal. I don't see a way to add and subtract datetime objects directly in jinja or how to properly get this to change without reloading the whole page?
Any ideas?

Polymer Dart - How can I read when core-list-dart is populated with data for a loading spinner?

Dart and Polymer Dart.
I am using many core-list-dart Lists in my program that populate with data upon page changed (using core-pages). I am finding that even though core-list-dart populates much quicker than using <template repeat="...>, it still causes several seconds delay (up to 8 seconds if there's enough data) when switching to a new page.
Fine. I understand that I'm using a beta version of polymer (and consequently Polymer Dart), and things will be slower. So for the sake of end-user sanity, I want to put up a loading spinner when I change pages. I can use futures to check for data populating the List being used, but that's not where the delay really occurs. The List populates with the data and the spinner goes away, and then the delay kicks in while the core-list-dart takes its sweet time, apparently, looping through the list or something.
How can I (or can I even) deal with keeping a loading indication (a spinner in my case -- specifically paper-spinner) up until the data with the core-list-dart is in place and ready to display.
Here is a specific example of the html code:
<core-list-dart id="list1" class="{{listclass}}" data="{{tierOne}}" grid="true" width="150">
<template>
<div index="{{index}}" class="{{ {'strike': model.cleared} }} ringcontainer">
<img _src="../../../web/images/rings/thumbnails/{{model.image}}" class="{{ {'strike': model.cleared} }} ringimagethumb" data-sku="{{model.SKU}}" data-finish="{{model.finish}}" on-click="{{zoomRing}}"/>
<core-selector theme="core-light-theme" on-core-select="{{removeRing}}" multi>
<core-item icon="{{model.icon}}" data-sku="{{model.SKU}}" data-finish="{{model.finish}}" class="{{ {'strike': model.cleared} }} ringdata">{{model.added}}</core-item>
</core-selector>
<div index="{{index}}" class="{{ {'strike': model.cleared} }} ringdata">Category: {{model.category}}</div>
<div index="{{index}}" class="{{ {'strike': model.cleared} }} ringdata">SKU: {{model.SKU}}</div>
<div index="{{index}}" class="{{ {'strike': model.cleared} }} ringdata">Finish: {{model.finish}}</div>
<div index="{{index}}" class="{{ {'strike': model.cleared} }} ringdata">${{model.price}}</div>
<div index="{{index}}" class="{{ {'strike': model.cleared} }} ringdata">(tier{{model.tier}}-id{{model.id}})</div>
</div>
</template>
</core-list-dart>
That is all within a core-pages tag and when the selected page changes to that section, this is the code that populates the list (initialized as #observable List tierOne = toObservable([]);) Ring, obviously, is the custom class I have used and tierData is the List of Rings that contains all of the data.
tierOne = tierData.where((Ring element) => element.tier == 1).toList();
This all works great. But it is slow -- particularly when being run on the tablets that the app is used on in the field.
Of course I am only presuming that the delay is with the core-list-dart -- as the core-pages swaps quite quickly otherwise.
Thanks
I haven't tried with core-list-dart but usually you'd do this with the unresolved class.
https://www.polymer-project.org/0.5/docs/polymer/styling.html#fouc-prevention
something like (not tested):
<style>
#spinner {
opacity: 100;
position: absolute;
}
body[unresolved] #spinner {
opacity: 0;
}
</style>
<body unresolved>
<img id="spinner" src=spinner.gif>
<core-list-dart></core-list-dart>
</body>