How can I access specific array in twig for symfony? - arrays

I have a problem, I only want to access a specific location of array,
Lets say I have this code
{% set total = val.listCompanies|length%}
{% if total > 1 %}
<td>
<button id="viewcompany"
type="button"
class="pop btn btn-info"
data-toggle="popover"
title="User Company List"
data-content='
{% for key1, val1 in val.listCompanies %}
{{ val1.CompanyName }}<br>
{% endfor %}'
data-placement="right"
data-html = "true">
see company
</button>
</td>
{% endif %}
{% if total < 2 %}
<td>
{% for key1, val1 in val.listCompanies %}
<center>
{{ val1.CompanyName }}<br>
</center>
{% endfor %}
</td>
{% endif %}
I want to make a button, that if it contain only one array inside it, I dont have to use the popover button, but if it has more than 1 array inside of its, then I have to show it inside of the popover button.
The thing is I cant access the specific array, to add more logic..

If your val.listCompanies contains numeric keys, you can access the first one by using:
val.listCompanies[0]
If your val.listCompanies has generated keys and you want to access the first one, you can use:
val.listCompanies|first
If your val.listCompanies has generated keys and you want to access the Nth one, you can use:
val.listCompanies|slice(n, 1)|first
Working demo

Related

HubL / Twig: Not finding value from array

In HubSpot, I've created a custom module called footer. footer has five field types of menu:
I've created an array where all five of the above menu ID's are pushed to an array. I've done this via a template partial file which is included in my footer module.
<!-- creating array -->
{% set footer_id_array = [] %}
<!-- push menu id's to array -->
{% do footer_id_array.append(module.menus.menu_column_1) %}
{% do footer_id_array.append(module.menus.menu_column_2) %}
{% do footer_id_array.append(module.menus.menu_column_3) %}
{% do footer_id_array.append(module.menus.menu_column_4) %}
{% do footer_id_array.append(module.menus.menu_column_5) %}
Running {{ footer_id_array }} shows all the IDs in the array, i.e.
[29420054435, 29420223163, 29420054590, 29420158158, 29420071857]
So this is correct, the array contains the IDs.
Now, for each item in this array, I want to generate a nav, so in my footer custom module, I have the following:
{% set iterations = range(0, 5) %}
{% for i in iterations %}
<nav>
{% menu id="{{ footer_id_array[i] }}" %}
</nav>
{% endfor %}
However, on my page, this just prints HubSpots default menus, not the ones assigned to the ID's.
Why is this?

if same id is present in two tables show edit button else show assign button in django

Get all the employee profile table id and check the id with employee process,if id matches show edit button in templates else show assign button.
Views.py
def Employee(request):
emp = Emp_Profile.objects.filter(is_active=True)
emptable = Emp_Profile.objects.values_list('id')
print(emptable)
empprocess = Emp_Process.objects.values_list('username_id').distinct()
print(empprocess)
obj = {}
for i in range(len(empprocess)):
obj[i] = empprocess[i]
return render(request, 'employee.html',{'list' : emp,'empprocess':empprocess,'obj':obj})
templates
{% for list in list %}
{% if obj != list.id %}
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Edit</button></a>
</td>
{% else %}
<h6>welcome</h6>
<td>
<a href="/view_client_process/{{ list.id }}"><button
class="btn btn-info">Assign</button></a>
</td>
{% endif %}
{% endfor %}
You can construct a set of username_ids and pass this to your template:
def Employee(request):
empS = Emp_Profile.objects.filter(is_active=True)
empprocess = set(Emp_Process.objects.values_list('username_id', flat=True).distinct())
return render(request, 'employee.html', {'emps' : emps, 'empprocess': empprocess })
In the template, we can then make a membership check of the set:
{% for emp in emps %}
<td>
{% if emp.id not in empprocess %}
<button class="btn btn-info">Edit</button>
{% else %}
<button class="btn btn-info">Assign</button>
{% endif %}
</td>
{% endfor %}
Note: you might want to rename your field username to user since a ForeignKey to a user is not the same as a username.
Note: please use {% url ... %} template tags [Django-doc] instead of performing URL processing yourself.

looping over jekyll collections

I have the following code
<div>
{% for note in site.regnotes %}
{% if note.regulationno == page.regulationno %}
<p>
{{ note.regulationno }} - {{ note.url }}
</p>
{% endif %}
{% endfor %}
</div>
This code loops over the regnotes collection in a jekyll site, checks if the current note regulationno is the same as the page regulationno and if so displays the regulationno and url - that is the url of the current page. How do I change this code to include the url of the previous page, the current page and the next page. I'm looking for three urls - previous, current and next? - The "page.previous.url" variable within jekyll does not appear to work in collections.
This is what it might look like in other code
for i=1 to number of items in the regnotes collection
if current note == page note
print page[i].url //current page url
print page[i-1].url //previous page url
print page[i+1].url //next page url
end if
end for
I suppose what I'm trying todo is reference the items in the collection by their array index. just can't seem to get the syntax correct.
Since you are a programmer, you just need to know that you need to use forloop.index0 to know where you are in the for loop (https://docs.shopify.com/themes/liquid-documentation/objects/for-loops#index0).
The code will be something like:
<div>
{% for note in site.regnotes %}
{% assign current_index = forloop.index0 }}
{% assign next_index = current_index | plus: 1 %}
{% assign prev_index = current_index | minus: 1 %}
{% if note.regulationno == page.regulationno %}
<p>
{{ note.regulationno }} - {{ note.url }}
</p>
{% if site.regnotes[prev_index] %}prev{% endif %}
{% if site.regnotes[next_index] %}next{% endif %}
{% endif %}
{% endfor %}
</div>

Output array in Twig

I trying to output an array from the database to the screen.
In my entity:
/**
* #ORM\Column(type="array", nullable=true)
*/
private $category;
In my twig template:
{% for category in user.profile.category %}
{{ category }}
{% endfor %}
Error: Array to string conversion in ...
Where is my mistake?
So, as error shows you are trying convert array (in category variable) to string. You can preview array by dump() (doc.). In your case:
{% for category in user.profile.category %}
{{ dump(category) }}
{% endfor %}
Please notice that dump() should be use only for debugging.
You can use join to output an array as a concatenated string. It behaves like implode() in php.
Example:
{{ [1, 2, 3]|join }}
{# returns 123 #}
{{ [1, 2, 3]|join('|') }}
{# outputs 1|2|3 #}
{{ [1, 2, 3]|join(', ', ' and ') }}
{# outputs 1, 2 and 3 #}
See the twig join documentation.
TWIG doesn't know how you want to display your table.
By the way, you should consider naming your variable $categories instead of $category, as you table contains several categories.
Then try this:
{% for category in user.profile.categories %}
{{ category }}
{% endfor %}
If my answer doesn't help, please give us the structure of your array (is there any keys or sub-arrays in you table or is it just a list?)
For anybody who want to output an associative array easily :
(here, the array is user.profile.category)
<table>
<tr>
{% for key,value in user.profile.category[0] %}
<td>{{key|e }}</td>
{% endfor %}
</tr>
{% for cat in user.profile.category %}
<tr>
{% for cell in cat %}
<td>{{ cell|e }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>

google app angine template: loop and check the existence of the corresponding entity

I need to create a 100-cell table, and in each cell if the corresponding entity exists, display it's information, otherwise, display "Empty". How do I do that? The python program (Item has properties of "seqNumber" and "name"):
query = db.Query(Item)
items = query.fetch(100)
render(..., {'range100':range(100), 'items':items}, ...)
HTML:
<table>
<tr>
{% for i in range100 %} <!-- for item in items (how?) -->
<td>
{% if item.seqNumber == forloop.counter (how?) %}
{{item.name}}
{% else %}
Empty
{% endif %}
{% endfor %}
</tr>
</table>
query = db.Query(Item)
items = query.fetch(100)
l = []
for i in enumerate(range(99)):
try:
l.append((i,items[i].name))
except:
l.append((i,None))
render(stuff = l)
This is all untested and the try/except is no doubt not ideal, just easier to write code then in a comment to give you the general idea of how I'd approach this.
<table>
<tr>
{% for i in stuff %}
<td>
{{ i.0 }}<!-- ID -->
{% if i.1 %}
{{ i.1 }}<!-- value -->
{% else %}<!-- if the value is none -->
"VALUE NEEDED"
{% endif %}
{% endfor %}
</tr>
</table>

Resources