How display "today" instead of today's date in TWIG? - date

I want to display "today" instead of the today's date, or "yesterday" instead of the previous day but I don't know do this in TWIG.
<p class="comment__date">{{ comment.createdAt|date('H:i d/m/Y') }}</p>
For the moment, I only get the date of publication of the comment.
An idea of ​​how can I do that ?
Thanks everybody

You could add an extra filter to solve this, e.g.
$twig->addFilter(new \Twig\TwigFilter('formated_date', function($date, $format = 'd-m-Y') {
$date = $date instanceof \DateTime ? $date : new \DateTime($date);
foreach(['today', 'yesterday',] as $state) if ($date >= new \DateTime($state)) return $state;
return $date->format($format);
});
Then use it inside twig, e.g.
{{ 'NOW' | formated_date }} {# output : today #}
{{ '19-09-2019' | formated_date }} {# output : today #}
{{ '18-09-2019' | formated_date }} {# output : yesterday #}
{{ '17-09-2019' | formated_date }} {# output : 17-09-2019 #}

try this
{% set datediff = date().diff(date(comment.createdAt)).days %}
{% if datediff > 365 %}
{{ (datediff/365)|round(0, 'floor') }} years ago
{% elseif datediff >= 30 %}
{{ (datediff/30)|round(0, 'floor') }} months ago
{% elseif datediff >= 7 %}
{{ (datediff/7)|round(0, 'floor') }} weeks ago
{% elseif datediff > 1 %}
{{ (datediff) }} days ago
{% elseif datediff %}
yesterday
{% else %}
today
{% endif %}
date() will return todays date
date().diff(...) will return diiference beetwen todays date and date when comment created
date().diff(...).days will return difference in days

You can do something like that :
{% set today = date() %}
{% set yesterday = date('-1days') %}
{% if comment.createdAt|date('d/m/Y') == today|date("d/m/Y") %}
{% set print_date = 'today' %}
{% elseif comment.createdAt|date('d/m/Y') == yesterday|date("d/m/Y") %}
{% set print_date = 'yesterday' %}
{% else %}
{% set print_date = comment.createdAt|date('H:i d/m/Y') %}
{% endif %}
<p class="comment__date">{{ print_date }}</p>

Related

How can I show form error one after the other ? (Condition 'elseif' not working)

I don't know how to show one form error one after the other when fields are empty : it worked for email, but not for password, gender, ect... I believe it comes from the condition I created because I get the proper error message when I remove them and paste them just outside the condition.
Where is be the mistake ?
register.html.twig
{% extends 'base.html.twig' %}
{% block main %}
{{ form_start(userform, {'attr': {'novalidate': 'novalidate'}} ) }}
{% set formErrors = userform.vars.errors.form.getErrors(true) %}
{{ dump(userform.vars.value.password|length) }}
{% if formErrors|length %}
<div class="alert alert-danger text-center" role="alert">
{% if userform.vars.value.email == null or userform.vars.value.email != 'email' or userform.vars.value.email != 'unique' %}
{{ form_errors(userform.email) }}
{% elseif userform.vars.value.password|length < 6 %}
{{ form_errors(userform.password.first) }}
{% elseif userform.vars.value.gender == null or (userform.vars.value.gender != 'male' and userform.vars.value.gender != 'female' and userform.vars.value.gender != 'non-binary') %}
{{ form_errors(userform.gender) }}
{% elseif userform.vars.value.firstname|length < 2 %}
{{ form_errors(userform.firstname) }}
{% elseif userform.vars.value.lastname|length < 2 %}
{{ form_errors(userform.lastname) }}
{% elseif userform.vars.value.birthdate == null %}
{{ form_errors(userform.birthdate) }}
{% elseif userform.vars.value.occupation|length < 2 %}
{{ form_errors(userform.occupation) }}
{% elseif userform.vars.value.nationality == null %}
{{ form_errors(userform.nationality) }}
{% elseif userform.vars.value.nativelanguage == null %}
{{ form_errors(userform.nativelanguage) }}
{% endif %}
</div>
{% endif %}
{{ form_errors(form) }} is not to do test if field is empty or not or is valid or not but just to display validations messages from Symfony Validator such Assert.
For exmple when you say:
{% if userform.vars.value.email == null %}
yes the first time when you comme on the url of form , the email is always null but this not how we test if email is blank, we don't test it in twig.
Keep in mind that {{ form_errors(form) }} is just for displaying errors messages, just for showing
Let's take this example :
class User implements UserInterface, \Serializable, PasswordAuthenticatedUserInterface
{
#[Assert\NotBlank(message: 'Email ne doit pas être vide')]
#[Assert\Email(message: 'Email n\'est pas valide')]
private ?string $email;
#[Assert\NotBlank]
#[Assert\Length(min: 3, max: 32, minMessage: 'msg min ...', maxMessage: 'msg max ....')]
private $plainPassword;
In User class we have already added a validation test if email is empty or is not valid usnig Assert.
The role of form_erros in twig is just showing this errors messages if they exists but not testing validation
So what you can do in twig is to test if form is valid or not, if not valid so display erros:
{% if not userform.vars.valid %}
{{ form_errors(userform.email) }} // if email is empty or not valid, it will show the message of Assert in user class
{{ form_errors(userform.firstName) }}
{{ form_errors(userform.lastName) }}
{{ form_errors(userform.plainPassword.first) }}
{% endif %}

Shopify linking product using SEO handle coding

I followed the directions for the second way to tag a product to a blog
This is the website I used https://happypoints.io/shopify-add-products-to-blog-post-c2-stt-66/ This is the code that was entered {% assign my_description = article.content | split: '=== split content ===' %}
{% assign my_description_size = my_description.size | minus: 2 %}
{{ my_description | first}}
<div class="show-product-list">
{% if article.tags.size > 0 %}
{% for tag in article.tags %}
{% paginate collections.all.products by 100 %}
{%- for product in collections.all.products -%}
{% if product.handle == tag %}
<div class="product_item">
{% include 'product-card-list' %}
</div>
{% endif %}
{%- endfor -%}
{% endpaginate %}
{% endfor %}
{% endif %}
</div>
{{ my_description | last}}
after following all the directions I received an error message saying
Liquid error (sections/article-template.liquid line 42): Could not find asset snippets/product-card-list.liquid
I am not sure why the product wont link to the blog using the seo handle. I have copied and pasted this code correctly and still getting this error
Collection code:
{% if collection.title == blank %}
{% assign collection_image = blank %}
{% elsif collection.image %}
{% assign collection_image = collection.image %}
{% else %}
{% assign collection_image = collection.products.first.featured_media.preview_image %}
{% endif %}
{% unless collection.title == blank %}
{% include 'card-image', type: collection_image, grid_style: grid_style %}
{% else %}
<div class="card__image-wrapper">
{% capture current %}{% cycle 1, 2, 3, 4, 5, 6 %}{% endcapture %}
{{ 'collection-' | append: current | placeholder_svg_tag: 'placeholder-svg' }}
</div>
{% endunless %}
<div class="card__info">
<h3 class="card__name h4">{% if collection.title != blank %}{{ collection.title }}{% else %}{{ 'homepage.onboarding.collection_title' | t }}{% endif %}</h3>
{% if section.settings.show_description and collection.description != blank %}
<div class="rte card__description{% if width == '2' %} card__description--padding{% endif %}">
{{ collection.description | strip_html | truncatewords: 15 }}
</div>
{% endif %}
</div>
You have correctly copy/pasted the code.
The problem is that your theme does not have a file named "product-card-list" in the snippets folder.
This is the file which contains code for the product tiles on the collection pages and the name for this file might differ in the theme that you're using.
You will need to find out the correct file name and replace "product-card-list" with that.
Can help you further if you share the code in your collection.liquid file.

Twig : unable to check if date is in last 2 years (prestashop)

I have the following in one of my prestashop.html.twig files.
{% for order in customerInformation.ordersInformation.validOrders %}
{% set mydate = order.orderPlacedDate %}
{{ order.orderPlacedDate }} - {{ mydate }}
{% endfor %}
This works correctly and pulls the order dates of any orders and outputs e.g.
14/02/2019 - 14/02/2019
08/03/2018 - 08/03/2018
15/08/2017 - 15/08/2017
06/04/2017 - 06/04/2017
depending on how many orders there has been.
Now I want to check to see if the order.orderPlacedDate aka mydate is over 2 years old.
So I did:
{% for order in customerInformation.ordersInformation.validOrders %}
{% set mydate = order.orderPlacedDate %}
{{ order.orderPlacedDate }} -
{% if date(mydate) > date('-2years') %}
OK {{ mydate }}
{% else %}
Over 2 years ago {{ mydate }}
{% endif %}
{% endfor %}
but this results in a 500 error.
An exception has been thrown during the rendering of a template
("DateTime::__construct(): Failed to parse time string (14/02/2019) at
position 0 (1): Unexpected character").
Tried changing the line
{% if date(mydate) > date('-2years') %}
to
{% if date(mydate) > date('-2years', 'Europe/Paris') %}
but that gave the error
An exception has been thrown during the rendering of a template
("DateTime::__construct(): Failed to parse time string
(order.orderPlacedDate) at position 0 (o): The timezone could not be
found in the database").
Can anyone see anything wrong with the above?
p.s im very new to twig (as in just heard about twig today!) so please keep explanations as simple as possible :)

Passing a macro argument to an if == test in jinja?

I'm using Tarbell to publish a formatted version of an inventory spreadsheet. Every row has a category, so I can do something like this:
<h2>Power Tools</h2>
{% for row in inventory %}
{% if row.Category == "powertools" %}
<b>{{ row.Display_Name|e }}</b> <br />
{% endif %}
{% endfor %}
<h2>A/V Gear</h2>
{% for row in inventory %}
{% if row.Category == "av" %}
<b>{{ row.Display_Name|e }}</b><br />
{% endif %}
{% endfor %}
To get a list of all the power tools followed by a list of A/V gear. I'd like to move that into a macro that I can call with a couple of arguments. I've got this:
{% macro list(cat, title='') -%}
<p>Category: {{ cat }}; Header: {{ title }}</p>
{% for row in inventory %}
{% if row.Category == "{{ cat }}" %}
<b>{{ row.Display_Name|e }}</b><br />
{% endif %}
{% endfor %}
{%- endmacro %}
When I call it with:
{{ list('av', title='Cameras and Audio Recorders')}}
{{ list('powertools', title='Power Tools')}}
I see "Category: powertools; Header: Power Tools" and "Category: av; Header: Cameras and Audio Recorders" as expected, so I know the macro can hear me, but the list itself doesn't show up. Can I use a macro argument in a comparison test? How?
There is no need for variable interpolation syntax inside of a block - you can just refer to the variable by name as you would in Python:
{# Do this #}
{% if row.Category == cat %}
{# Instead of this #}
{% if row.Category == "{{ cat }}" %}

symfony 2 form_row with 2 fields

I need something like below:
{% block form_row %}
<div class="form_row">
{{ form_label(form) }}
{{ form_widget(form) }}
{{ form_widget(form.field_name + '_previous') }}
{{ form_errors(form) }}
</div>
{% endblock form_row %}
i.e, two form fields in one row; second field name is equal to first_field_name + _previous.
For example, if field name is 'total_cost', then second field will be 'total_cost_previous'.
How can I do that?
i think you can do something like this:
{% set field = field_name ~ '_previous' %}
{{ form_widget(attribute(form, field)) }}