Using {{ myvariable }} in Nunjucks just prints "{{ myvariable }}" in final HTML file - html

I use Metalsmith with Nunjucks in a static site generator. In the project, I am importing a Nunjucks macro into a file and trying to invoke it using {{ someMacro }}. However, in the resulting HTML file, "{{ someMacro }}" gets printed as a string instead of the markup inside the macro.
I've also tried {% set someVariable = "abc" %}, and invoke the variable with {{ someVariable}}, both in the same file, but I get the same issue with "{{ someVariable }}" being printed right into HTML.
I've tried invoking both inside in a {% block xyz%} {% endblock %}. Any ideas?

I found my own answer. In the project I'm working on, we use Metalsmith in-place, and there our engineOptions looks like this:
const templateConfig = {
engineOptions: {
filters: {},
tags: {
variableStart: '<<<',
variableEnd: '>>>',
}
}
};
Instead of using {{ }} to use variables or macros, I just had to use <<< >>> to call variables or macros in the main file, and likewise when passing arguments into macros in macro files.

Related

SaltStack check if grain exists in Jinja file

I'm using SaltStack to manage my infra. Machines are hosted in different DCs, so they also have slightly different network setup.
Currently, I'm running into the following issue:
Comment: Unable to manage file: Jinja variable 'dict object' has no attribute 'macaddress'; line 9
---
[...]
ethernets:
{{ grains['interface_context'] }}:
dhcp4: {{ grains['dhcp4'] }}
dhcp6: {{ grains['dhcp6'] }}
addresses: [{{ grains['ipv4'] }}, "{{ grains['ipv6'] }}"]
{% if grains['macaddress'] %} <======================
match:
macaddress: {{ grains['macaddress'] }}
{% endif %}
routes:
- to: default
[...]
---
As the message indicates, the grain "macaddress" is missing, which I can confirm, it's not set for this minion. But What I do not understand is how I can simply check if this variable/grain exists at all within a jinja template?
I wouldn't expect this error to come up, as I actually wanted to catch it with the if statement.
Can somebody help?
Use get to return None instead of raising:
{% if grains.get('macaddress') is not none %}
Or if you want to treat "empty" values the same:
{% if not grains.get('macaddress') %}

Hugo/Docsy: execute of template failed at <.url>: can’t evaluate field url in type bool

I am developing a static web application using Hugo with Docsy theme. I would like to add an condition within Docsy Partials code where I would like to append the mailTo: word to my .url if the .mail is set to true, when I try to do this then I get the following error:
/themes/docsy/layouts/partials/footer.html:36:34": execute of template failed at <.url>: can’t evaluate field url in type bool
Following is the code I am adding to my partials:
{{ $myUrl := "" }}
{{ with .mail }}
{{ $myUrl = print "mailTo:" .url }}
{{ else }}
{{ $myUrl = .url }}
{{ end }}
{{ $myUrl }}
If I add some test then everything would work perfectly:
{{ with .mail }}
TRUE
{{ else }}
FALSE
{{ end }}
I am quite new to the Hugo and Docsy theme so finding difficult to understand and fix it. Any help would be really appreciated.
You are not using with correct here: https://gohugo.io/functions/with/. I think you should use if here.

Shopify Looping Over JSON Metafield Arrays

For some reason, I can't access an array within a JSON metafield.. I've tried the other StackOverflow answers, and I'm using value, etc. but just can't figure it out, here's my metafield:
product.metafields.artist.releases
with a value of:
{
  "releases": [
   { 
"id": 0,
    "releaseName": "lofi 1",
    "coverArt": "",
    "releaseLink": “”
},
 { 
"id": 1,
    "releaseName": " lofi 2",
    "coverArt": "",
    "releaseLink": “”
}
]}
(which formats to: "{\"releases\":[{\"id\":0,\"releaseName\":\"lofi 1\",\"coverArt\":\"\",\"releaseLink\":“”},{\"id\":1,\"releaseName\":\"lofi 2\",\"coverArt\":\"google.com\",\"releaseLink\":“”}]}")
and I'm using this in the product.custom.liquid:
{{ product.metafields.artist.releases.value }}
{% assign releases = product.metafields.artist.releases.value %}
{% for release in releases.releases %}
{{ release.releaseName }}
{% endfor %}
the first one shows up fine, and if I assign it and do {{ releases }} it shows up fine as well so I know the assignment is working, but I can't forloop over it (mind you that the first object in the JSON is also called releases (I've also tried renaming it all to unique names just in case and that didn't help))
For some reason when it is a multidimensional JSON array it acts weird. There is a simple fix for it, just add (-) at the end of your assigned variable:
{%- assign releases = product.metafields.artist.releases.value -%}
{% for release in releases.releases %}
{{ release.releaseName }}
{%- endfor -%}
Hope it solves your problem like it did mine!
Liquid is not going to work on JSON like this. If you want to iterate through an array of JSON objects, use Javascript.
As lov2code points out by adding (-) it trims the output for any unnecessary white space, which enables you to traverse the JSON array.

Google Deployment manager: MANIFEST_EXPANSION_USER_ERROR multiline variables

Trying to use Google Deployment Manager with YAML and Jinja with a multi-line variables, such as:
startup_script_passed_as_variable: |
line 1
line 2
line 3
And later:
{% if 'startup_script_passed_as_variable' in properties %}
- key: startup-script
value: {{properties['startup_script_passed_as_variable'] }}
{% endif %}
Gives MANIFEST_EXPANSION_USER_ERROR:
ERROR: (gcloud.deployment-manager.deployments.create) Error in
Operation operation-1432566282260-52e8eed22aa20-e6892512-baf7134:
MANIFEST_EXPANSION_USER_ERROR
Manifest expansion encountered the following errors: while scanning a simple key in "" could not found expected ':' in ""
Tried (and failed):
{% if 'startup_script' in properties %}
- key: startup-script
value: {{ startup_script_passed_as_variable }}
{% endif %}
also
{% if 'startup_script' in properties %}
- key: startup-script
value: |
{{ startup_script_passed_as_variable }}
{% endif %}
and
{% if 'startup_script' in properties %}
- key: startup-script
value: |
{{ startup_script_passed_as_variable|indent(12) }}
{% endif %}
The problem is the combination of YAML and Jinja. Jinja escapes the variable but fails to indent it as YAML would require when being passed as a variable.
Related: https://github.com/saltstack/salt/issues/5480
Solution: Pass the multi-line variable as an array
startup_script_passed_as_variable:
- "line 1"
- "line 2"
- "line 3"
The quoting is important if your value starts with # (which startup script on GCE does, ie #!/bin/bash) since it will be treated as a comment otherwise.
{% if 'startup_script' in properties %}
- key: startup-script
value:
{% for line in properties['startup_script'] %}
{{line}}
{% endfor %}
{% endif %}
Putting it here since there aren't much Q&A material for Google Deployment manager.
There is no clean way to do this in Jinja. As you yourself have pointed out, because YAML is a whitespace-sensitive language, it is difficult to effectively template around.
One possible hack is to split the string property into a list and then iterate over the list.
For example, providing the property:
startup-script: |
#!/bin/bash
python -m SimpleHTTPServer 8080
you can use it in your Jinja template:
{% if 'startup_script' in properties %}
- key: startup-script
value: |
{% for line in properties['startup-script'].split('\n') %}
{{ line }}
{% endfor %}
Here is also a full working example of this.
This method will work, but generally cases like this are when people start considering using a python template. Because you are working with an object model in python, you do not have to deal with indentation problems. For example:
'metadata': {
'items': [{
'key': 'startup-script',
'value': context.properties['startup_script']
}]
}
An example of the python template can be found in the Metadata From File example.

Comparing variables in template to build JSON - Ansible

Starting off with Ansible and I am trying to use ReST API to interact with an external application.Maybe I am missing something simple here.
I am trying to compare every host in my inventory file with the POD name specified in the variable file used by the role that invokes the jinja2 template.
My inventory file looks like this:
[all]
'POD-9'
'POD-10'
Variable file :
pods:
params:
- name: POD-9
- name: POD-10
{% for pod in pods.params %}
{% if '{{ inventory_hostname }}' == '{{ pod.name }}' %}
<generate JSON template here>
{% endif %}
{% endfor %}
The if statement however does not take effect. I want the template to be generated only in the inventory_hostname is equal to the pod name in the variable file
The current JSON file includes both :
{
"pod": {
"name": "POD-9"
}
"pod": {
"name": "POD-10"
}
}
In Jinja2 the double curly braces are used as a print statement. If you access variables inside tags don’t put the braces around them
{% for pod in pods.params %}
{% if inventory_hostname == pod.name %}
<generate JSON template here>
{% endif %}
{% endfor %}
Found the problem :
{% if pod.name == inventory_hostname %}