As nunjucks now supports using set as a block I wanted to do something like this:
{% set navigationItems %}
{% for item in items %}
{ name: item.name, url: item.url }{% if not loop.last %},{% endif %}
{% endif %}
{% endset %}
Then call this variable as the input object on another macro, like so:
{{ navigation(items=[navigationItems]) }}
However, navigationItems is evaluated as a string, not an array-literal. Any idea how, or if this is possible?
Thanks.
I'm not exactly sure what you're trying to accomplish. It looks like you want to loop over one array called items and copy it into a new array called navigationItems. Perhaps items contains more keys than you want to pass to the macro?
I'm going to make that assumption, otherwise you could simply copy items into navigationItems like so:
{% set navigationItems = items %}
This example works:
{% macro navigation(items) %}
<ul>
{% for item in items %}
<li>{{ item.name }} - {{ item.url }}</li>
{% endfor %}
</ul>
{% endmacro %}
{% set websites = [
{
name: 'Google',
url: 'http://google.com',
description: 'A search engine'
},
{
name: 'GitHub',
url: 'http://github.com',
description: 'A webapp for your git repos'
},
{
name: 'StackOverflow',
url: 'http://stackoverflow.com',
description: 'The answer: 42'
}] %}
{% set navigationItems = [] %}
{% for website in websites %}
{% set navigationItems = (navigationItems.push({name: website.name, url: website.url}), navigationItems) %}
{% endfor %}
{{ navigation(items=navigationItems) }}
websites values contain a description key which is not passed on to the navigationItems array. If it were me, I'd just pass website directly to the navigation macro since your keys: name and url are the same in both arrays.
The pattern here is almost like a map method in Javascript or Ruby.
Related
I am using Django and Chart.js, but I don't think what's more important here is an understanding of Javascript and HTML.
To create charts using Chart.js, I need the charts to have different names. For this, I have thought about using a counter variable.
<script>**var count = 0;**</script>
<ul>
{% for object in objects %}
<li>
...
<script>
{% block jquery %}
console.log(count);
var endpoint = '/api/chart/data/';
fetch(endpoint, {
method: "GET",
}).then(response => response.json())
.then(data => {
console.log('Success:', data);
**count = count + 1;**
...
eval('var chart_id = "myChart{{ count }}"');
eval('var ctx{{ count }} = document.getElementById(chart_id)');
eval('var myChart = new Chart(ctx{{ count }}, graph_data)');
console.log("myChart{{ count }}")
})
.catch((error) => {
console.log("Error:")
console.log(error);
});
{% endblock %}
</script>
<canvas id= "myChart{{ count }}" width="400" height="400"></canvas>
...
</li>
{% endfor %}
</ul>
However, when I look in the source code on my dev server, I can see that the id for all of the canvas tags is simply "myChart". Why is this? What am I doing wrong?
Try this:
{{ forloop.counter }} will return the current iteration count going on.
<ul>
{% for object in objects %}
<li>
...
<script>
{% block jquery %}
console.log(count);
var endpoint = '/api/chart/data/';
fetch(endpoint, {
method: "GET",
}).then(response => response.json())
.then(data => {
console.log('Success:', data);
...
eval('var chart_id = "myChart{{ forloop.counter }}"');
eval('var ctx{{ forloop.counter }} = document.getElementById(chart_id)');
eval('var myChart = new Chart(ctx{{ forloop.counter }}, graph_data)');
console.log("myChart{{ forloop.counter }}")
})
.catch((error) => {
console.log("Error:")
console.log(error);
});
{% endblock %}
</script>
<canvas id= "myChart{{ forloop.counter }}" width="400" height="400"></canvas>
...
</li>
{% endfor %}
</ul>
I have an SMS function on my Django app, but I want to happen is record the message and timestamp each time I send a message. I need to store the value inside sms_message on another table every time I click send sms.
The entry on the other table will be like this:
id: 1
Description: As of {z.timestamp}, the Rainfall Warning is now at {z.level}. Please prepare for evacuation
Timestamp: XXXXX
Help, how to do it? Thanks!
#views.py
def send_sms(request):
aws_access_key_id = "XXXXXXXXXXXX"
aws_secret_access_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
aws_region_name = "us-east-1"
z = Rainfall.objects.latest('timestamp', 'level')
sender_id = "Test"
sms_message = f'As of {z.timestamp}, the Rainfall Warning is now at {z.level}. Please prepare for evacuation'
client = boto3.client(
"sns",
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=aws_region_name
)
topic = client.create_topic(Name="notifications")
topic_arn = topic['TopicArn'] # get its Amazon Resource Name
numbers = Mobile.objects.all()
for i in numbers:
client.subscribe(
TopicArn=topic_arn,
Protocol='sms',
Endpoint=i.mobile_number
)
response = client.publish(
Message=sms_message,
TopicArn=topic_arn,
MessageAttributes={
'string': {
'DataType': 'String',
'StringValue': 'String',
},
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': sender_id
}
}
)
messages.info(request, 'SMS sent successfully!')
return HttpResponseRedirect('/advisory/')
#sendsms.html
{% block content %}
{% if messages %}
{% for message in messages %}
{% if message.tags %} <script>alert("{{ message }}")</script> {% endif %}
{% endfor %}
{% endif %}
<form method="post" action="{% url 'send_sms' %}">
{% csrf_token %}
<button class="btn btn-danger btn-block btn-round">Send SMS</button>
</form>
{% endblock content %}
I use Hexo hexo.io, but I guess Jekyll users may know this too as it is similar.
My custom.post.variable is fruit.
So my .md files have:
title: food
fruit: apple
and
title: more food
fruit: banana
and
title: still more food
fruit: banana
and
title: try some food
fruit: banana
and
title: enjoy food
fruit: apple
How to count all posts with fruit: apple?
I know that my custom post.variable is not site -wide, so that is my problem.
I tried to put my post.fruit variable as a function in site.posts.length but that did not work.
Use Liquid to iterate through the list of posts. Whenever a post has the fruit field set to apple, then increment a counter.
{% assign postCount = 0 %}
{% for post in site.posts %}
{% if post.fruit == "apple" %}
{% assign postCount = postCount | plus: 1 %}
{% endif %}
{% endfor %}
The number of posts with 'fruit: apple' is {{postCount}}
I have data coming from the database as the below format on query execution
[(‘Country-1’, ‘state1’), (‘Country-1’, ‘state2’), (‘Country-1’, ‘state3’),
(‘Country-2’, ‘state1’), (‘Country-2’, ‘state2’), (‘Country-2’, ‘state3’),
(‘Country-3’, ‘state1’), (‘Country-3’, ‘state2’), (‘Country-3’, ‘state3’)]
I want to convert to as this resultset as below format
context = {
'countries': [ { 'Countryname': 'country1’,
'state': [ { 'Statename': 'state1'},
{'Statename': 'state2'},
{'Statename': 'state3'} ]
},
{ 'Countryname': 'country2’,
'state': [ { 'Statename': 'state1'},
{'Statename': 'state2'},
{'Statename': 'state3'} ]
},
{ 'Countryname': 'country3’,
'state': [ { 'Statename': 'state1'},
{'Statename': 'state2'},
{'Statename': 'state3'} ]
}
]
}
So that I can iterate the data in the in HTML in Django to create the tree format:
<ul class = "myUL">
{% for country in data %}
<li class = "caret"> {{ country.countryname }} </li>
<ul class="nested">
{% for state in country.statename %}
<li>{{state.statename}}</li>
{% endfor %}
</ul>
{% endfor %}
Expected output for HTML is:
Country-1
State1
State2
State3
Country -2
State1
State2
State3
Country -3
State1
State2
State3
Try the following:
Data parser:
data = [('Country-1', 'state1'), ('Country-1', 'state2'), ('Country-1', 'state3'), ('Country-2', 'state1'), ('Country-2', 'state2'), ('Country-2', 'state3'), ('Country-3', 'state1'), ('Country-3', 'state2'), ('Country-3', 'state3')]
reformatted_data = {}
for pair in data:
state_list = reformatted_data.get(pair[0], None)
if state_list:
if pair[1] in state_list:
pass
else:
reformatted_data[pair[0]].append(pair[1])
else:
reformatted_data[pair[0]] = [pair[1]]
# Try this print in your console to make sure it's working properly
print(reformatted_data)
Template to display data:
<ul class = "myUL">
{% for country, statelist in data.items %}
<li class = "caret"> {{ country }} </li>
<ul class="nested">
{% for state in statelist %}
<li>{{ state }}</li>
{% endfor %}
</ul>
{% endfor %}
In Apostrophe, I have a custom module where I would like to pass an option from the Nunjucks apos.area call to the construct method of the widget itself. Concretely, I want to adjust the output of getWidgetWrapperClasses based on the options passed to the module in the template. Is this possible?
Here's an example of what I would like to achieve:
lib/modules/example-widgets/index.js
module.exports = {
extend: "apostrophe-widgets",
label: "Example widget",
construct: function(self, options) {
self.getWidgetWrapperClasses = function(widget) {
// templateOptions would be the options object as defined
// in home.html below
return ["column", "column-" + templateOptions.width];
};
}
};
lib/modules/apostrophe-pages/views/pages/home.html
{% extends "layout.html" %}
{% block content %}
<div id="widgets">
{{ apos.area(data.page, "example", {
widgets: {
"example": {
width: "half"
}
}
}) }}
</div>
{% endblock %}
I solved this by not using the getWidgetWrapperClasses method, but instead extending the widget wrapper template and overriding a Nunjucks block in there. This is in fact a documented approach if you look in lib/modules/apostrophe-areas/views/widgetBase.html in Apostrophe's code.
I changed lib/modules/example-widgets/index.js like this:
module.exports = {
extend: "apostrophe-widgets",
label: "Example widget",
wrapperTemplate: "wrapper",
construct: function(self, options) {
// Do something
}
};
Then, I added a lib/modules/example-widgets/views/wrapper.html file. In that file, you can simply override the extraWrapperClasses block to add the classes you want, all the while having access to the template options through data.options.
{% extends "apostrophe-areas:widget.html" %}
{% block extraWrapperClasses %}column column-{{ data.options.width }}{% endblock %}