for instance
<div class="price">{{blocks.quantity}} x {{blocks.price}} </div>
i want to multiply price by quantity
data from Json file.
var nunjucks = require('nunjucks');
var env = nunjucks.configure();
env.addFilter('mysum', function (arr) {
return arr
.map(e => e.quantity * e.price) // get amount to each e
.reduce((sum, e) => sum + e, 0) // calc total summa
});
var data = [
{price: 10, quantity: 2},
{price: 2, quantity: 7},
{price: 5, quantity: 11}
]
var res = env.renderString(`{{ data | mysum }}`, {data});
console.log(res);
There are multiple ways to do this, including building filters.
One simple way would be to define it in the template where you will use the value:
{% set total_price = blocks.quantity * blocks.price %}
You could then say:
I will sell you {{ blocks.quantity }} apples for {{ blocks.price }} each, the
total price will be {{ total_price }}.
You could also then use this in the logic:
{% if total_price > 100 %}
Price per apple is {{ blocks.price }}
{% else %}
Price per apple is {{ blocks.price * 0.9 }}
{% endif %}
Finally you can just express it like this {{blocks.quantity*blocks.price}}, as previous commenter Sauntimo said already.
You should be able to execute mathematical operations inside double curly braces like this:
<div class="price">{{blocks.quantity*blocks.price}}</div>
See the docs at https://mozilla.github.io/nunjucks/templating.html#math
Related
I'd like to show the list's introduction to users, and I've used the Association rule in Django for this project.
views.py
def user_detail(req, id):
AllParcel = Add_Parcel.objects.filter(id=id).first()
df = pd.read_csv('myapp/recommend.csv')
df = df.drop_duplicates().reset_index(drop=True)
df = df.pivot(index='item_id', columns='user_id', values='user_id')
df = df.notnull().astype(int)
frequent_itemsets = apriori(df, min_support=0.5, use_colnames=True)
rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.5)
user_loans = LoanParcel.objects.filter(user=req.user)
user_borrowed = [loan.parcel_item.name for loan in user_loans]
recommended_items = []
for item in rules['antecedents']:
if set(item).issubset(set(user_borrowed)):
recommended_items.extend(list(Add_Parcel.objects.filter(name__in=rules[rules['antecedents'] == item]['consequents'].tolist()[0])))
context = {
"AllParcel": AllParcel,
"recommended_items" : recommended_items,
}
return render(req,'pages/user_detail.html',context)
I wanted to render recommended_items to display similar to Add_Parcel using data from Add_Parcel's database to display, but when I put the display command in HTML, it returned as a blank value. How should I fix it?
user_detail.html
<h2>Recommended Items</h2>
<ul>
{% for parcel in recommended_items %}
<li>{{ parcel.name }} ({{ parcel.nametype }}) - {{ parcel.description }}</li>
{% endfor %}
</ul>
recommend.csv
item_id,user_id
1,1
1,2
1,3
1,4
1,5
1,6
1,7
3,8
3,9
3,10
3,11
1,12
1,11
1,10
2,9
2,8
2,7
I want to print to get the details of different cities weather and I had written the code as below. While retrieving the data, I am not able to fetch the data to HTML.
views.py:
from django.shortcuts import render
# Create your views here.
import urllib.request
import json
import requests
def display(request):
city=['vijayawada','guntur','tenali','rajahmundry','amaravathi']
for i in city:
source = urllib.request.urlopen(
'https://api.openweathermap.org/data/2.5/weather?q=' + i + '&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read()
list_of_data = json.loads(source)
data = {
"country_code": str(list_of_data['sys']['country']),
"coordinate": str(list_of_data['coord']['lon']) + ', '
+ str(list_of_data['coord']['lat']),
"temp": str(list_of_data['main']['temp']) + ' °C',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
'main': str(list_of_data['weather'][0]['main']),
'description': str(list_of_data['weather'][0]['description']),
'icon': list_of_data['weather'][0]['icon'],
}
print(data)
return render(request, "display.html",data)
display.html:
<html>
<head>
<title>API Display</title>
</head>
<body>
<h1>Weather details</h1>
<form>
{% for i in data %}
{{ country_code }}
{{ temp }}
{{ i }}
{% endfor %}
</form>
</body>
</html>
I am trying to print the values of the dictionary to html but not getting printed. The values are printing correctly in the console which means the for loop in views.py is working correctly.
Please tell me where I am wrong
You might want to make a function that handles the request for each city:
def get_city_weather(city_name):
source = urllib.request.urlopen(
'https://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read()
list_of_data = json.loads(source)
return {
"country_code": str(list_of_data['sys']['country']),
"coordinate": str(list_of_data['coord']['lon']) + ', '
+ str(list_of_data['coord']['lat']),
"temp": str(list_of_data['main']['temp']) + ' °C',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
'main': str(list_of_data['weather'][0]['main']),
'description': str(list_of_data['weather'][0]['description']),
'icon': list_of_data['weather'][0]['icon'],
}
Then use dict comprehension to compile the data dict to send to the template:
def display(request):
cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi']
data = {city_name: get_city_weather(city_name) for city_name in cities}
return render(request, "display.html", data)
At this point data is a dictionary who's key is the city name and who's value is the dictionary returned by get_city_weather, so it looks like (abbreviated):
{'vijayawada':
{'country_code': 'ABC'
# ...
}
# ...
}
Then in the template you could loop through this like:
{% for city_name, city_weather in data.items %}
The temperature in {{city_name}} is {{city_weather.temp}}
and the air pressure is {{city_weather.pressure}}.
{% endfor %}
Or if you don't want to specify the keys like temp and pressure, you could do:
{% for city_name, city_weather in data.items %}
<p>Weather data for {{city_name}}:</p>
<ul>
{% for k,v in city_weather.items %}
<li>{{k}}: {{v}}</li>
{% endfor %}
</ul>
<hr />
{% endfor %}
That is because you are overwriting your data dictionary. It's being passed only as one object, it should render something if you try {{data}} or {{data.country_code}}, {{data.temp}}...
One way to solve this, is to have a nested dictionary with the data of every city:
views.py
def loop_dict(request):
cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi']
data = {}
for city in cities:
source = urllib.request.urlopen(
'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read()
list_of_data = json.loads(source)
data[city] = {
"country_code": str(list_of_data['sys']['country']),
"coordinates": {
'latitude': str(list_of_data['coord']['lat']),
'longitude': str(list_of_data['coord']['lon'])
},
"temp": str(list_of_data['main']['temp']) + ' °C',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
'main': str(list_of_data['weather'][0]['main']),
'description': str(list_of_data['weather'][0]['description']),
'icon': list_of_data['weather'][0]['icon'],
}
context = {'data': data}
return render(request, 'loop_dict.html', context)
loop_dict.html:
{% extends 'base.html' %}
{% block content %}
{% for key, obj in data.items %}
<h2>City: {{key}}</h2><br>
<p>Country Code: {{obj.country_code}}</p><br>
<p>Latitude: {{obj.coordinates.latitude}}</p><br>
<p>Longitude: {{obj.coordinates.longitude}}</p><br>
<p>Temp: {{obj.temp}}</p><br>
<hr>
{% endfor %}
{% endblock %}
AFAIK, django template system recognizes dict variable just like Python itself does.
So, if we try to convert your template code back to Python code, we would get something like this:
for i in data:
print(country_code)
print(temp)
print(i)
Now, ask yourself: will it work?
Obviously, it's not.
So, how exactly in Python you would loop and access dict values?
You can do it like this:
for i in data:
print(i)
Or with k,v loop variables (better way):
for k, v in enumerate(data):
print(f"key: {k}, value: {v}")
But, in your template code, you are trying to access certain values with the key (country_code etc).
In this case, you probably don't even need to use the for-loop.
And your display.html file can be rewritten like this:
<html>
<head>
<title>API Display</title>
</head>
<body>
<h1>Weather details</h1>
<form>
{{ data.country_code }}
{{ data.temp }}
</form>
</body>
</html>
Also, as I can see your view retrieves this data for each given city.
Thought you only pass the last one to your template.
In order to fix this, you must rewrite your view code.
I guess you could add a new variable called collected_data and then at the end of every data retrieve loop just append data to this new variable.
After that, you could just pass the collected_data to the template.
And then loop through it within the template.
But I exactly don't know how your template should look like, so I leave it to you.
I've tried to explain what's the issue is.
I am trying to display the currency name or key like "USD", "AUD", "EUR" with their respective "last" and "buy" properties from this HTTP response:
and I just get back a list of "key" strings like this
but I can't figure out why my "key" is being returned as a string here.
It's making it difficult for me to programmatically access the properties for each currency
this is my dashboard.component.ts
prices;
bitcoinOwned;
ngOnInit(): void {
this.data.getPrice()
.pipe(map(result => {this.prices = result, console.log("result", result)
for (let key in result) {console.log( key)}
} ))
.subscribe();
}
my data.service
getPrice() {
var url = "https://blockchain.info/ticker";
return this.http.get(url);
}
and my template
<div>
{{ prices |json }}
</div>
<div>
USD last: {{ prices?.USD.last |json }} USD sell: {{ prices?.USD.sell |json }}
</div>
I can access the properties when I do it manually for each key like this but I need to iterate over the keys and do it more programmatically so any help would be appreciated!!
You may want to use Angular's KeyValuePipe.
Then, you can do something like this:
<div *ngFor="let item of prices | keyvalue">
{{item.key}} last: {{ item.value.last |json }} {{item.key}} sell: {{ item.value.sell |json }}
</div>
I think you can use Object.keys() on the object to return the key value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
I want to get the records based on days for example
1) > 180 days = number of records created
2) 90 to 180 days = number of records created
3) 60 to 90 days = number of records created
4) 30 to 60 days = number of records created
But I am not getting the exact result. Is this the correct way to do it?
what I have tried in the blade view
<?php
$date1 = \Carbon\Carbon::today()->subDays(180);
$date2 = \Carbon\Carbon::today()->subDays(90);
$date3 = \Carbon\Carbon::today()->subDays(60);
$date4 = \Carbon\Carbon::today()->subDays(30);
?>
in blade
{{ \App\Claim::where('created_at','>=', $date1)->count() }}
{{ \App\Claim::where('created_at','>=', $date2)->where('created_at','<', $date1)->count() }}
{{ \App\Claim::where('created_at','>=', $date3)->where('created_at','<', $date2)->count() }}
{{ \App\Claim::where('created_at','>=', $date4)->where('created_at','<', $date3)->count() }}
{{ \App\Claim::where('created_at','<=', $date4)->count() }}
Try this code
?php
$date1 = \Carbon\Carbon::today()->subDays(180)->format('Y-m-d');
$date2 = \Carbon\Carbon::today()->subDays(90)->format('Y-m-d');
$date3 = \Carbon\Carbon::today()->subDays(60)->format('Y-m-d');
$date4 = \Carbon\Carbon::today()->subDays(30)->format('Y-m-d');
?>
in blade
{{ \App\Claim::whereDate('created_at','>=', $date1)->count() }}
{{ \App\Claim::whereDate('created_at','>=', $date2)->whereDate('created_at','<', $date1)->count() }}
{{ \App\Claim::whereDate('created_at','>=', $date3)->whereDate('created_at','<', $date2)->count() }}
{{ \App\Claim::whereDate('created_at','>=', $date4)->whereDate('created_at','<', $date3)->count() }}
{{ \App\Claim::whereDate('created_at','<=', $date4)->count() }}
Note : Make variables date format Y-m-d
The angularjs app doesn't show me any result.
It shows me :
Name City Order Total joined
{{ cust.name }} {{ cust.city }} {{ cust.orderTotal }} {{ cust.joined }}
What is the reason of this type of error !!!
Update 1:
function CustController($scope)
{
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'},
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'},
{joined: '240-344-55', name:'jone', city:'usa', orderTotal:'231'}
];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
}
If you are using $scope approach, then you have to remove "cust." part from your view. It would be {{ name }} {{ city }} etc.
But if your view has ng-controller="CustController as cust", that means you are using "controller as" syntax, so you would need to refactor your controller code, changing $scope. to this. everywhere at least.