How to access objects in Jekyll array? - arrays

My Jekyll page code is as following (simplified):
_layouts/content.html:
---
layout: null
---
<pre>
{{ content }}
</pre>
any_page.md
---
layout: content
social:
- twitter :
url : "https://twitter.com"
user : "foo"
show : true
- instagram :
url : "https://instagram.com"
user : "bar"
show : false
---
My understanding of above in any_page.md is
social is an array of objects having items 0, 1; social[0] equals to * twitter. These keys can be variable.
each array item in above array is social[i]; an object having similar known keys (url, user, show)
Problem:
How to access page.social[i]["url"] & other two known keys?
How to access these known keys of an object residing in a variable-length array?
How to get the following outputs: twitter, https://twitter.com, foo, true
Code I have tried:
all social array: {{ page.social }} outputs (as expected)
{“twitter”=>
{ “url”=>”https://twitter.com”,
“user”=>”foo”,
“show”=>true
}
}
{“instagram”=>
{ “url”=>”https://instagram.com”,
“user”=>”bar”,
“show”=>false
}
}
social array's first object: {{ page.social[0] }} outputs (as expected)
{“twitter”=>
{ “url”=>”https://twitter.com”,
“user”=>”foo”,
“show”=>true
}
}
Failed attempts to access url of item 01 (all results to empty):
{{ page.social[0]["url"] }}
{{ page.social[0][url] }}
{{ page.social[0]."url" }}
{{ page.social[0].url }}
{{ page.social[0][0] }}
Addendum:
I have also tried the for loop; & it gives all the values on root level (twitter etc..), but no access to the object keys:
{% for item in page.social %}
item = {{ item }} # works
item[URL] = {{ item[url] }} # empty
item["URL"] = {{ item["url"] }} # empty
item."URL" = {{ item."url" }} # empty
item.URL = {{ item.url }} # empty
i = {{forloop.index }} # ok, but starts from 1 instead of 0
{% endfor %}

This will work:
twitter key: {{page.social[0]|first|first}}
<h2>data</h2>
url: {{page.social[0]['twitter'].url}}
user: {{page.social[0]['twitter'].user}}
show: {{page.social[0]['twitter'].show}}
Another approach
social:
twitter :
url : "https://twitter.com"
user : "foo"
show : true
instagram :
url : "https://instagram.com"
user : "bar"
show : false
Then you can access it with:
{% for item in page.social%}
key: {{item[0]}}<br>
{% endfor %}
<hr>
<h2>data</h2>
url: {{page.social['twitter'].url}}
user: {{page.social['twitter'].user}}
show: {{page.social['twitter'].show}}

I have accepted marcanuy's answer, here I am just documenting what I used based on his answer;
{% for item in page.social %} # OUTPUT for 1st item
{{ item[0] }} # twitter:
{{ item[1].url }} # https://twitter.com
{{ item[1].user }} # foo
{{ item[1].show }} # true
{% endfor %}
Also, the declaration in front matter is bit changed. The one which works with above code is:
social:
twitter :
url : "https://twitter.com"
user : "foo"
show : true
instagram :
url : "https://instagram.com"
user : "bar"
show : false
Note the missing - dashes. Although both ways are correct, I need to read more to how to access both.
As mentioned at http://yaml.org/spec/1.2/spec.html, indentations & - matter. Each item having more spaces than earlier makes itself child of earlier.

Related

ansible loop variable in a template

in a j2 ansible template, I have below section:
{% for action in actions %}
my-{{ action }}-job: |-
{{ lookup('template', 'files/myjobs.yaml.j2' ) | indent(width=4) }}
{% endfor %}
actions is defined in another yaml:
actions:
- check
- action1
- action2
playbook:
vars:
cert_manager_enabled: true
roles_array:
- testtask
role testtask:
- name: Create resources for test deployment
k8s:
state: present
namespace: "testns"
definition: "{{ lookup('template', item.name) | from_yaml }}"
loop:
- name: myjob.yaml.j2
when I run the playbook, error with below message:
The task includes an option with an undefined variable. The error was:
'action' is undefined
the action is a loop variable, any solution to inject a loop variable into lookup('template', ....)?
from here,
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_lookup.html#parameter-template_vars.
I saw there is a dict param named "templated_vars", but when I passed value like below:
{{ lookup('template', 'files/myjobs.yaml.j2', template_vars={'action': action} ) | indent(width=4) }}
it does not work...
is it an ansible bug?

Hugo data template telephone number gets rendered as a hash

I have a weird problem with Hugo and data templates.
I have link content in a json data template that i try to render inside an a tag like so:
data/foobar.json:
{ [ { link: 'tel:+123123', text: 'a' }, { link: 'mailto:mail#example.com', text: 'b' ] }
partial.html:
{{ range .Site.Data.foobar }}
{{ .text }}
{{ end }}
Which Produces:
a
b
For some reason the first anchor target renders out as a random hash, but the second one correctly. This seems to happen only when i start the link with tel:, and i can't understand why?
Probably syntax should be: {{ .link | safeURL }}
https://gohugo.io/functions/safehtml/
https://gohugo.io/functions/safehtmlattr/#readout
https://gohugo.io/functions/safeurl/
https://gohugo.io/functions/urlize/#readout
This is intentional as the link is not being sanitized.
See docs on Go and the way elements are rendered.
Off the cuff and not near my station - one of the above will point you in the right direction.
Check it and let me know.

How to display array as text? - Laravel

I tried this way to show this the data but it's not working:
Blade file:
#foreach($test->item['0'] as $link)
{{ $link['item1'] }}
#endforeach
Controller file:
public function testingview()
{
$test = Test::get()->toArray();
return view('Admin.test')->with('test', $test);
}
I want to show something like that:
Item1: 123, adsf, dd, abcd
Item2: on, on, true, true
You could try something like this:
#foreach($test->item['0'] as $link)
Item 1: {{ implode(" ,", $link['item1']) }}
#endforeach
The implode function takes an array, puts it together, and returns it as a string. I encourage you to read more about implode().

AngularJS / HAML : Add CSS class if property is true

I work in customizing element of an ItemSelector directive, data of ItemSelector coming from rails server.
here is the haml code :
.directive-items-selector{ ng_click: "openItemsSelector( $event )" }
.wrapper
%ui_select.ui-select{ ng: { model: "input.model", disabled: "disabled",
change: "itemSelectModelChanged()" },
search_enabled: "{{ options.searchable }}" }
%ui_select_match.ui-select-match{ items_selector_match: '',
placeholder: "{{ input.placeholder }}",
allow_clear: "{{ options.clearable }}",
title: "{{ $select.selected.label }}" }
%i.fa{ ng_class: 'icon' }
{{ $select.selected.label }}
%i.archived.fa.fa-archive{ ng_if: '$select.selected.object.is_archived' }
%span.archived{ translate: 'archived.yes' }
%ui_select_choices.ui-select-choices{ repeat: "item.id as item in input.filteredItems track by item.id",
refresh: "reloadItems( $select.search )",
refresh_delay: '{{ input.filterDelay }}' }
.item{ ng_attr_title: "{{ ::item.label }}" }
.item-label {{ ::item.label }}
%small.item-details {{ ::item.details }}
.items-selector-actions
%a.pointer.action{ ng: { if: 'linkToModal', click: 'openDetails()', disabled: "!model" }}
{{ 'btn.details' | translate }}
%a.pointer.action{ ng: { if: 'createButton && klassName && !disabled', click: 'createItem()' }}
{{ 'btn.new' | translate }}
I test if the object selected is archived or not by :
$select.selected.object.is_archived
for now I'm adding an icon and a small text to tell user that this object selected is archived, what what I want is to change that and add
text-decoration: line-through red; to be like that :
how to add css class depend on $select.selected.object.is_archived value
Ng-class accepts object, where key is your class and value is condition, when it is to be applied:
ng-class="{'desiredClass': $select.selected.object.is_archived}"
Or another solution is using ternary operator:
ng-class="$select.selected.object.is_archived ? 'desiredClass' : ''"
In HAML, via various usages:
%div{'ng-class': "{'desiredClass': condition === true}"}
%div{'ng_class': "{'desiredClass': condition === true}"}
%div{'ng': {'class': "{'desiredClass': condition === true}"}}
Here working codepen example:
https://codepen.io/anon/pen/pKreGv?editors=1010

Get the right value out of the right array-entry in MongoDB / Twig

I'm trying to get a value from an array inside a mongodb collection.
My db entries look like:
_id : "somerandomid"
page : "page1"
entries : [ {
id : "id1"
entry : "content"
}
{
id : "id2"
entry : "content2"
} ]
I want to match page : "page1" first, then find the right entry in the 'entries' array based on 'id', then display the 'content' of that entry.
I tried: {% set rightentry = mydb.find({page : "page1", id : "id1" }) %}
{{rightentry.content}}
but that doesn't give me anything back.
db.page.find({page:"page1", "entries.id":"id1"})
this will bring back the desired results.
You won't be able to retrieve only the subdocument that matches your query from MongoDB directly.
You'll want to iterate over the entries that are returned with your retrieved document to find the one that matches:
{% set document = mydb.find({page:"page1", "entries.id":"id1"}) %}
{% for entry in document.entries %}
{% if entry.id === "id1" %}
{# display contents #}
{% endif %}
{% endfor %}

Resources