Count posts with custom post.variable - javascript

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}}

Related

How to insert data into a database every time I click Send from HTML button

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 %}

How to modify shopify reorder to cart to add custom line item properties

I am trying to add a reorder button to my customer's order history pages to automatically reorder items they've already purchased. This would send them back to the cart with items already prefilled and ready for checkout. Each product item has custom properties attached to it. Everything seems to work fine, except that when I add the items back into the cart, I cannot get the custom line item properties to display.
I'm using the order-to-cart.liquid snippet.
On line 18, it seems the custom properties are being called:
properties: {{ line_item.properties | json }}
I've tried to modify the code to add them:
request.send(JSON.stringify({
'quantity':order.items[0].quantity,
'id':order.items[0].variant_id,
'properties':order.items[0].properties
}));
But this does not work.
Based on the comment below, I tried to loop through the item properties:
request.send(JSON.stringify({
'quantity':order.items[0].quantity,
'id':order.items[0].variant_id,
'properties': {
{% for line_item in order.line_items %}
{% for property in line_item.properties %}
'{{ property.first }}': '{{ property.last }}'{% unless forloop.last %},{% endunless %}
{% endfor %}
{% endfor %}
}
}));
But I get syntax error:
SyntaxError: missing } after property list
note: { opened at line 403, column 26
Which seems to reference the property list of request.send
The outputted example json is:
/* Setup the order object. Extend this as needed. */
var order = {
items:[
{
variant_id: 16320547225634,
product_id: 1782978904098,
properties: [["Arrangement Type",""],["Enclosed Card",""],["Occasion \u0026amp; Comments","Condolescens"],["Delivery Date","Mar 29, 2019"]],
available: true
},
{
variant_id: null,
product_id: 1776316743714,
properties: [["Arrangement Type",""],["Enclosed Card",""],["Occasion \u0026amp; Comments",""],["Delivery Date","Mar 24, 2019"]],
available: null
},
{
variant_id: 16319970017314,
product_id: 1782916808738,
properties: [["Arrangement Type","Seasonal"],["Enclosed Card","Love and best wishes"],["Occasion \u0026amp; Comments","Just Because"],["Delivery Date","Mar 25, 2019"]],
available: true
},
{
variant_id: 16311468687394,
product_id: 1780877819938,
properties: [["Arrangement Type","Large vase with orchids"],["Enclosed Card","Steal the warm chair right after you get up when owners are asleep, cry for no apparent reason sleeps on my head."],["Occasion \u0026amp; Comments","Birthday so make extra special!"],["Delivery Date","Apr 10, 2019"]],
available: true
}
]
};
request.send(JSON.stringify({
'quantity':order.items[0].quantity,
'id':order.items[0].variant_id,
'properties': {
'Arrangement Type': '',
'Enclosed Card': '',
'Occasion & Comments': 'Condolescens',
'Delivery Date': 'Mar 29, 2019'
'Arrangement Type': '',
'Enclosed Card': '',
'Occasion & Comments': '',
'Delivery Date': 'Mar 24, 2019'
'Arrangement Type': 'Seasonal',
'Enclosed Card': 'Love and best wishes',
'Occasion & Comments': 'Just Because',
'Delivery Date': 'Mar 25, 2019'
'Arrangement Type': 'Large vase with orchids',
'Enclosed Card': 'Steal the warm chair right after you get up when owners are asleep, cry for no apparent reason sleeps on my head.',
'Occasion & Comments': 'Birthday so make extra special!',
'Delivery Date': 'Apr 10, 2019'
}
}));
My cart.liquid file calls the custom properties like so:
{% if property_size > 0 %}
{% for p in item.properties %}
{% assign first_character_in_key = p.first | truncate: 1, '' %}
{% unless p.last == blank or first_character_in_key == '_' %}
<div class="label-info">{{ p.first }}:
<strong class="input-info">{{ p.last }}</strong>
</div>
{% endunless %}
{% endfor %}
{% endif %}
But I'm not sure if I need to modify this to accommodate any properties already created.
The custom line item properties need to show up when added back to the cart, otherwise the reorder function won't really be a time saver as it will force customers to go back to each product page to re-add info into the custom fields.
I'm not that versed in liquid so not quite sure what needs to be done to modify the snippet or cart templates. Any help you could provide would be greatly appreciated!
Many thanks,
Mark
The reason 'properties':order.items[0].properties does not work is because it contains an array with the name and value of the line item property.
To set this up we will need to turn the array into and object and then pass that into the request.send function.
A function I found that achieves this can be seen in this post. You can copy and paste this function into the orderItems function.
Once that is added we then create the properties variable, passing in order.items[0].properties as an argument to turn this into an object.
This variable is added along with the 'quantity' and 'id' in request.send.
Here is how the orderItems function will look once everything is added:
/* Simple function add to cart */
var orderItems = function(){
if(!order.items.length){ return }
if(!order.items[0].available){
checkQueue();
}
function objectify(array) {
return array.reduce(function(p, c) {
p[c[0]] = c[1];
return p;
}, {});
}
var properties = objectify(order.items[0].properties);
var request = new XMLHttpRequest();
request.open('post', '/cart/add.js', true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onload = function() {
var resp = request.responseText;
if (request.status >= 200 && request.status < 400) {
checkQueue();
} else { /* add your error handling in here */ }
};
request.onerror = function() {
/* add your error handling in here */
};
request.send(JSON.stringify({
'quantity':order.items[0].quantity,
'id':order.items[0].variant_id,
properties
}));
};
Hope that helps!

tree structure in html with dynamic content

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 %}

Access template options in module's construct method

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 %}

nunjucks set create object

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.

Categories