error while generating json object from python dictionary using django_template json_script - django-templates

I am trying to get a "json" object from a python dictionary using djnago template "json_script",which is throwing "template syntax error"
//html code
{{ value|json_script:"hello-data" }}
<script>
var Value=JSON.parse(document.getElementById("hello-data").textContent);
document.write(Value);
</script>
//views.py
from django.shortcuts import render
from django.http import HttpResponse
import random as ran
# Create your views here.
def indees(request):
vals={"123":"abc","Key":"value","hello":"user"}
return render(request,"verbat.html",context={"value":vals})

The context is the template context dictionary, you cannot access it as a single dict, you can only access its members (keys).
Read here or here for more.
E.g., In your example, you can access 'bool', 'list_' and 'msg', but probably you want to access a dictionary with these three keys.
So you need to put your data inside inner key and use it. Something like:
//views.py
def indes(request):
list_of_vals=[ran.randint(12,34),ran.randint(44,55)]
data={"bool":"True",
"list_":list_of_vals,
"msg":"hello"}
return render(request,"base.html",context={'data':data})
And inside index.html, to have:
{{ data|json_script:"hello-data" }}

Related

NUXT pass object data into pages with path

I'm really new to Vue and Nuxt so I apologise if this is a simple question.
I'm generating my routes dynamically on making an API call for my data on Index.vue. One API call is enough for me to retrieve all the data i need which is stored in deals_array, so I don't need another API call on my individual page, I just need the data from each deal in deals_array.
<ul>
<li v-for="deal of deals_array" :key="deal.id">
<nuxt-link :to="getSlug(deal)">{{ deal.name }}, {{deal.value}}</nuxt-link>
</li>
</ul>
I'm wondering how do I pass the entire deal object into my pages, so that when I click on the individual nuxt-link I would be able to access that deal object and all its attributes (for each page).
I've taken a look at passing params into nuxt-link but I understand that it only pairs with name attribute and not the path, where I need the path URL in this case.
I may be doing this entirely wrong so I'm hoping to be pointed in the right direction.
Edit - getSlug function
getSlug(deal) {
let name = deal.name;
let dealDetails = deal.details;
let name_hyphen = name.replace(/\s+/g, "-");
let deal_hyphen = dealDetails.replace(/\s+/g, "-");
let nameDealSlug = name_hyphen + "-" + deal_hyphen;
// remove selected special characters from slug
let clean_nameDealSlug = nameDealSlug.replace(
/[&\/\\#,+()$~%.'":*?<>{}]/g,
""
);
let finalSlug = `deals/${clean_nameDealSlug}`;
return finalSlug;
}
I'm assuming you have gone through this: https://router.vuejs.org/api/.
You can just pass the entire object:
<nuxt-link :to="{ path: 'test', query: {a: 1, b: 2}}">Test Page</nuxt-link>
And your URL will become something like this:
http://localhost:3000/test?a=1&b=2
The entire object can be simply passed.
This will be available to your next page in $route object in the url query.
Otherwise if you don't want to get your deal object exposed just use the concepts of vuex. Store the entire deal object in the vuex and pass ids to different pages. And from pages retrieve the deal object through vuex.

Object relational mapping ('and_' not working)

and_ is not working
can anyone help me out. i am new to flask
test.py
from flask import session,Flask,render_template,request
from models import *
import os
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
#app.route('/')
def index():
query= book.query.filter(and_ (book.title=='we all lost',book.publication_year==2050)).all()
for i in query:
print(i.title)
return render_template('hellotesting.html',m=query)
hellotesting.html
<html>
<head></head>
<body>
<ol>
<li>{{m.title}} </li>
<li>{{m.author}} </li>
<li>{{m.publication_year}}</li>
</ol>
</body>
</html>
error
NameError
NameError: name 'and_' is not defined
i dont know why it is not working
You need to import it before you can use it
from sqlalchemy import and_
and then
query = book.query.filter(and_(book.title=='we all lost',book.publication_year==2050)).all()
Also in your hellotesting.html file you try to display attribute of queryset (something like list of your model instances), not particular object and it will raise exception. You have to get any object from queryset in function or in template before call it's attribute.
In function you can do something like
query = book.query.filter(and_(book.title=='we all lost',book.publication_year==2050)).first()
or
book = query[0]
and then put that object to render_template function or you can do something similar in template like
{{ m[0].title }}
Read documentation for more examples and explenations

VueJS: :class, condition with index

I'm creating a list of (thumbnail) 2 images, and #click each image should be expanded to max-width, by adding said class ('max-w-full') to the classes. The class is added by setting the array entry with the same index nr. as the image (imgclicked[0], imgclicked[1]) in the list to 1.
data:() {
imgclicked=[0,0], //by default both are set to 'small'/not 'max-w-full'
},
the template part looks like this:
<template v-for="(image,index) in images>
<a #click="zoomImgClicked(index)">
<img :src="image.filename" :class={'max-w-full' : imgclicked[index]==1,'w-12' : imgclicked[index]==0}">
</a> // using this.imgclicked[index] gives me the error 'this.imgclicked[0] is undefined'
</template>
on click the method zoomImgClicked() ist launched:
zoomImgClicked: function(i){
if(this.imgclicked[i]==0){
this.imgclicked[i]=1
}else{
this.imgclicked[i]=0
}
},
But this is not working. If I open the vue console and change the values of imgclicked[0] manually from 0 to 1 it works (images ae being resized). Also I see the method doing it's work, when logging in the console, the values are changed from 0 to 1 and vice versa. But it's not reflected on the page #click.
Why is that?
Please read Change Detection Caveats in the Vue docs.
Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g. vm.items.length = newLength
You should use the $set method for this:
this.$set(this.imgclicked, i, 1)
try with array syntax:
<img
:src="image.filename"
:class="[
{
'max-w-full': imgclicked[index]==1,
'w-12': imgclicked[index]==0
},
'static class if need'
]"
>

Make JSON visible from page without using imports in vuejs

I'm trying to make a simple webpage in Vuejs.
I have a Main.vue page, which has an import of a json file, and this json file contains certain parameters. One of them is an object array, each of its elements has a string indicating the page to be shown next in a sequence. The page also fetches data from that object.
So, the Main.vue can access to every field and object of the json file file and shows the pages (page1, page2, page3...) in a sequence, depending on the information stored at that object array.
These pages (page1, page2, page3...) need to be generic, with no reference to a specific json file, and need to show information from that specific object of the array of the json.
I know how to pass data to pages via URL (so, for example, "page1" knows which element of the array has to fetch info from because Main.vue specifies it in the URL) but I don't know how can I make MyJson accesible to "page1", "page2" without making an import sentence of MyJson in each page.
I do not have backend or something similar, just a frontend which executes entirely in the browser.
I was wondering whether there is any way of accessing MyJson from page1, page2, page3... without having a backend.
Many thanks in advance
Regards
Miguel
I have tried it by passing info via URL, but it didn't work out as expected.
PS: This is my json
MyJson.json
{
"id"="whatever"
"text"="whatever"
"myArray"=[
{
"whichPageHasToRenderMe"="page1"
"myData"= ...
...
},
{
"whichPageHasToRenderMe"="page2"
"myData"= ...
...
},
{
"whichPageHasToRenderMe"="page1"
"myData"= ...
...
},
{
"whichPageHasToRenderMe"="page1"
"myData"= ...
...
}
]
}
If you serve your json file as static file. You can use fetch api or any other fetch library to access your json file.
fetch('path/to/your.json')
.then(response => response.json())
.then(data => {
// do something
})
See more about Fetch API.
In case you want to pass some json data as url query. Don't forget to use encodeURIComponent or btoa to escape some special characters.
window.open('/some/path?data=' + encodeURIComponent(JSON.stringify(data)))
I have solved it by using Vuex and setting the JSON in the state of Vuex, so it can be accessible from other pages.

AngularDart: using template input variables in structural directives

I have learning AngularDart. Everything went well so for. But I am stuck with structural directives : I cannot figure out how to use the template input variables to implement my own structural directive.
I read many times this document: Structural Directives.
And, although the material below refers to AngularJS, I read this questions/documents:
Angular 2: How to access Template Input Variables in Structural Directives
Angular 2 Custom Structural Directive binding using template input variable is not working
How to use Angular structural directive with multiple inputs
Or, how I wrote a customized version of ngFor
It is said that from the micosyntax declaration "let v=value", Angular creates the template variable "let-v". However, I cannot use the name "let-v" in a template since "let-v" is not a valid name for a variable.
By the way, if you look at the explanation that is given here for the directive ngFor :
<div *ngFor="let hero of heroes; let i=index; let odd=odd; trackBy: trackByHeroId"
[class.odd]="odd">
({{i}}) {{hero.name}}
</div>
<template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd"
[ngForTrackBy]="trackByHeroId">
<div [class.odd]="odd">({{i}}) {{hero.name}}</div>
</template>
You see that, inside the template, the template input variable i is called i (not let-i):
<div [class.odd]="odd">({{i}}) {{hero.name}}</div>
I tried a LOT of things within the Dart code of my structural directive. But nothing works.
I read the source code for the directive NgFor. Something potentially interesting here :
viewRef.setLocal('first', identical(i, 0));
viewRef.setLocal('last', identical(i, len - 1));
viewRef.setLocal('index', i);
viewRef.setLocal('count', len);
However, I tried that with no success.
Here is the simple code I wrote:
File: lib/src/directive_my_dummy.dart
import 'package:angular/angular.dart';
#Directive(
selector: '[myDummy]'
)
class MyDummyDirective implements OnInit {
TemplateRef _templateRef;
ViewContainerRef _viewContainer;
MyDummyDirective(TemplateRef templateRef, ViewContainerRef viewContainer) {
_templateRef = templateRef;
_viewContainer = viewContainer;
}
#Input('let-d')
List<int> d;
void ngOnInit() {
print("One instance of MyDummyDirective is instantiated.");
EmbeddedViewRef vr = _viewContainer.createEmbeddedView(_templateRef);
vr.setLocal('d', [1,2,3]);
print(d.toString());
}
}
File: lib/app_component.html
<div *myDummy="let d=data">
This is a dummy test. {{d.toString()}}
</div>
<div *myDummy="let d=[1,2,3]">
This is a dummy test. {{d.toString()}}
</div>
<div *myDummy="let d=getData()">
</div>
<div *myDummy="let d=[1,2,3]; let name='Toto'"></div>
The full code can be found here.
Can you show me a basic example that illustrates the use of the template input variables ?
First, there are two entities that we call "template":
The component template.
The (structural) directive template.
The term "input template variable" makes reference to the (structural) directive template.
I think that it would be better to use the appellation "input directive template variable".
I'll use the appellation "input directive template variable" instead of "input template variable".
The role of an input directive template variable is to configure a (structural) directive template.
Where does the value of an input directive template variable come from ?
The answer is: the value of an input directive template variable gets assigned within the directive instance. You cannot define the value of an input directive template variable directly within the component template. For example, the code <div *myDummy="let d=10"> below will NOT assign the value 10 to the variable d.
The value of the input directive template variable is assigned from within the directive instance. For example:
TemplateRef _templateRef;
ViewContainerRef _viewContainer;
// ...
_viewContainer.createEmbeddedView(_templateRef);
_viewContainer.get(0).setLocal('data', 'MyDummyDirective.data');
And you write, within the component template:
<div *myDummy="let d=data">
I give a simple example:
lib/src/directive_my_dummy.dart
#Directive(
selector: '[myDummy]'
)
class MyDummyDirective implements OnInit {
TemplateRef _templateRef;
ViewContainerRef _viewContainer;
#Input('myDummyVariable')
String variable;
MyDummyDirective(this._templateRef, this._viewContainer);
void ngOnInit() {
// WARNING: the property "variable" has no value assigned within the constructor.
_viewContainer.createEmbeddedView(_templateRef);
_viewContainer.get(0).setLocal('data', 'MyDummyDirective.data');
print('MyDummyDirective.variable = ${variable}');
_viewContainer.get(0).setLocal('var', 'This is ' + variable);
}
}
lib/app_component.html
<div *myDummy="let d=data; variable:'value from the lib/app_component.html'; let v=var">
<p>This is a dummy directive.</p>
<ul>
<li><b>d</b>=<code>{{d.toString()}}</code></li>
<li><b>data</b>=<code>{{data}}</code> (makes reference to the instance of AppComponent)</li>
<li><b>v</b>=<code>{{v}}</code></li>
</ul>
</div>
lib/app_component.dart
import 'package:angular/angular.dart';
import 'package:myapp/src/directive_my_dummy.dart';
#Component(
selector: 'app-component',
templateUrl: 'app_component.html',
directives: [MyDummyDirective],
)
class AppComponent {
List<int> getData() => [100, 200, 300];
String data = 'AppComponent.data';
}
The result:
This is a dummy directive.
<ul>
<li>d=MyDummyDirective.data</li>
<li>data=AppComponent.data (makes reference to the instance of AppComponent)</li>
<li>v=This is value from the lib/app_component.html</li>
</ul>
EDIT:
As a picture often speaks better than words...