I have a array called 'Posts' in twig.
Is there a way to easily remove the first item of this array?
So it's structure is just like this:
array('post 1','post 2','post 3')
And I was wondering if the first post can easily be removed with a function in twig to this:
array('post 2','post 3')
You're looking for the slice filter.
The slice filter extracts a slice of a sequence, a mapping, or a string:
{% for i in ['post 1', 'post 2', 'post 3'] | slice(1) %}
{{ i }}
{% endfor %}
output
post 2
post 3
The slice filter works as the array_slice PHP function for arrays and mb_substr for strings with a fallback to substr.
Related
I am working on search part of my project. On one of my filter, I have to use sorted() function. Code:-
posts = Post.objects.filter(title__icontains=query)
posts = sorted(posts, key=lambda obj: obj.titleFilter())
But, in other filters in the project, I don't have to use sorted as it can be done with django annotate and so on. So, in the template I usually have to do posts.count except for the title filter.
My template, code:-
<div>{{ posts.count }} results found.</div>
I know, I can use if cases in template to work and apply length function like:
<div>
{% if title_filter %}
{{ posts|length }}
{% else %}
{{ posts.count }}
{% endif %} results found.
</div>
Also, I am not sure if length should be fine as there were some article not to use length for querysets.
Thank you!!! Feel free to ask.
After doing sorted posts is no longer a QuerySet.
You can do this
posts = Post.objects.filter(title__icontains=query)
count = posts.count()
posts = sorted(posts, key=lambda obj: obj.titleFilter())
send count as a variable
I'm learning to use the Craft CMS, which uses Twig templating. I'm trying to output a JSON object in Twig, but instead of 2 items in the JSON I'm getting info about a single item.
Here is my code:
{% set newsitems = craft.entries.section('newsitems').orderBy('PostDate desc').limit(100) %}
{% set response = [] %}
{% for newsitem in newsitems %}
{{ 'Here' }}
{% set response = response|merge({'type':0, 'id':newsitem.id, 'link':newsitem.sourceLink}) %}
{% endfor %}
{{ response|json_encode() }}
And here is the output I get:
Here Here {"type":0,"id":"25","link":"https:\/\/gadgets.ndtv.com"}
As can be seen, the loop executes two times ('Here' is printed 2 times) but there is only one item in the JSON array which is printed.
Am I missing something basic? Any help would be appreciated. Thanks in advance.
Twig's merge filter uses array_merge in the background.
The manual states the following
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
This is what is happening to your output, in the first iteration you've create an associative array with the key: type, id, link. In the x'th iteration you are just overwriting the values stored in said keys. The solution is also stated in the manual, numeric indices will be appended to the array instead of overwriting it.
In twig you would solve it as this:
{% set response = [] %}
{% for newsitem in newsitems %}
{% set response = response|merge([{ 'type': 0, 'id': newsitem.id, 'source': newsitem.source,},]) %}
{% endfor %}
{{ response|json_encode|raw }}
demo
I have a text like: 000325175
and I want to format it as: 000 325 175.
Nothing's easier (in theory) with the split filter, as:
{{ mynumber|split('', 3) }}
But I get a
An exception has been thrown during the rendering of a template ("Notice: Array to string conversion")
However I can apply a slice filter without any problem.
{{ mynumber|slice(9, 14) }}
So I don't understand. Thanks for help
The split filter return an array (with the spitted values), you should only iterate over the result to display it as follow:
{% for partial in mynumber|split('', 3) %}
{{ partial}}
{% endfor %}
Here a working solutions
EDIT:
You can also use the join filter and concatenate the results as example:
{{ mynumber|split('', 3)|join(' ') }}
How in twig to set 2 dimentional array in macros and to run it?
I did :
{{ components.menu_item( "Hostels", 'hostel', {'admin/hostel/index': 'All Hostels'}, {'admin/hostel/active_featured_listings': 'Active Featured Hostels'} ) }}
{% macro menu_item(title, active_admin_link, items_array) %}
title::{{ title }}<br>
items_array::{{ dump(items_array) }}<br>
{% endmacro %} {# menu_item END #}
But only 1st array elemented was outputted
array (size=1) 'admin/hostel/index' => string 'All Hostels' (length=11)
What is rigth way and how make for circle?
Thanks!
From the Twig doc:
["foo", "bar"]: Arrays are defined by a sequence of expressions
separated by a comma (,) and wrapped with squared brackets ([]).
So try surround the input with squared brackets, as follow:
{{ components.menu_item( "Hostels", 'hostel', [{'admin/hostel/index': 'All Hostels'}, {'admin/hostel/active_featured_listings': 'Active Featured Hostels'}] ) }}
Hope this help
Is it possible to directly access an array index from within a Twig template?
Here's my setup, using Silex:
return $app['twig']->render('template', array('numbers' => array('one', 'two', 'three')));
so can I do something like this?
{{numbers[0]}}
Just before posting this I realized, that's exactly what you can do, but as I didn't find the answer anywhere in the docs or google (correct me if I'm wrong), I've posted this anyway.
{{numbers[0]}}
The answer of Adam, is correct, only to make it clear and improve,
you can have access directly to array index
{{ myArray[0] }}
if you need to access in a loop
{% set arrayOfItems = ['ZERO', 'ONE'] %}
{% set myArray = ['APPLE', 'ORANGE'] %}
{% for oneItem in arrayOfItems %}
<p>{{ oneItem }} equals {{ myArray[loop.index0] }}</p>
{% endfor %}
in this example I used an array inside a non related loop so the result is:
ZERO equals APPLE
ONE equals ORANGE
Thats actually something what doesnt work for me when using Twig with shopware 6.
I try to access an object like
{{ page.cart.lineItems.elements[0].quantity }}
what will lead into a parsing error of the Twig Template
I can use
{{ page.cart.lineItems.elements | first }}
to get the first Element, but dont know how i can then access a property of this first element