Nunjucks nested variables - html

Are nested variables possible in Nunjucks? I need to be able to store a string in my database containing Nunjucks variable but it does not seem to work. Here's an example of what I need to be able to do:
dict = {
name: 'John',
lastname: 'Smith',
greeting: 'Hello, my name is {{ name }} {{ lastname }}'
}
And then be able to do
<span>{{greeting}}</span>
but it outputs this:
'Hello, my name is {{ name }} {{ lastname }}'
The reason i need it this way it because I have a database with some description templates with holes and i have a database with values and I need to be able to combine them. But it is not always the same values so I cant hard-code them.

The simplest way is a add global or filter
var nunjucks = require('nunjucks');
var env = nunjucks.configure();
env.addFilter('render', function(text) {
return nunjucks.renderString(text, this.ctx);
});
var res = nunjucks.renderString(
'name: {{name}}, greeting: {{greeting | render}}',
{
name: 'John',
greeting: 'Hello {{name}}'
}
);
console.log(res);

Related

UpdateValuesMissingError on typeorm transaction. NestJS

Code fragment look like this:
const data = {
title: title,
area: area,
category: category,
body: body,
fileUrl: image.path,
fileType: image.mimetype,
};
await queryRunner.manager
.createQueryBuilder()
.update(PostEntity)
.set(data)
.where('id = :id', { id })
.execute();
And when image.path is undefined or any value from data object, I got error
UpdateValuesMissingError: Cannot perform update query because update values are not defined. Call "qb.set(...)" method to specify updated values.
It works fine without transactions, undefined value in object means it doesn't assign new value to DB.

Quasar Q-Table and Data from Array (IndexedDB & Dexie)

I am new to Quasar and Javascript and I'm trying to get data from my database (IndexedDB using Dexie) into my q-table.
I have the skeleton of the q-table and I'm getting the data from Dexie, in the form of an Array, but I don't know how to display the data in the table and I would love some help.
I've read about maybe having to use computed, and/or the map option but I don't know enough about either of those to use them. I've been googling and reading the Quasar docs and I'm still not sure what to do. I don't know if I can put it in a codepen since it's getting data from a database.
I have this live online at https://entrypaws.com/ you may have to hit shift-reload to get the latest version as my host has an online cache it keeps, though I've cleared it. This small table section is reachable by clicking the 'view test table' link in the left sidebar.
Here is my html:
<q-page>
wholething: {{ this.thePersonArray }} // this displays correc
<br/><br/>
hmmm: {{ this.thePersonArray[0].f_lastName }}
<q-table
title="Treats"
:rows="rows"
:columns="columns"
row-key="name"
binary-state-sort
>
<template v-slot:body="props">
<q-tr :props="props">
<q-td key="name" :props="props">
{{ props.row.name }}
</q-td>
<q-td key="lname" :props="props">
{{ props.row.lname }}
</q-td>
<q-td key="dogbreed" :props="props">
<div class="text-pre-wrap">{{ props.row.dogbreed }}</div>
</q-td>
<q-td key="phone" :props="props">
{{ props.row.phone }}
</q-td>
</q-tr>
</template>
</q-table>
</q-page>
</template>
and this is my script:
import { ref } from "vue"
import theDB from "../components/dexiedb.js"
const columns = [
{
name: 'name',
label: 'First Name',
field: row => row.name, // f_lastname:
},
{ name: 'lname', label: 'Last Name', field: 'lname'},
{ name: 'dogbreed', label: 'Dog Breed', field: 'dogbreed'},
{ name: 'phone', label: 'Phone', field: 'phone'},
]
const rows = [
{
name: 'Susan',
lname: 'Smith',
dogbreed: 'Danish-Swedish Farmdog',
phone: '801.810.9990',
},
{
name: 'James',
lname: 'Jones',
dogbreed: 'Kromfohrlander',
phone: '801.930.9999',
},
]
export default {
name: "testtable",
setup() {
return {
columns,
rows
}
}, // end setup
data() {
return {
thePersonArray: [],
}
}, // end data
created() {
this.getTheUsers()
}, // end mounted
methods: {
getTheUsers() {
this.thePersonArray = []
console.log(" getTheUsers 1 ", this.thePersonArray)
this.thePersonArray.push({f_lastName: "Dreamer"}) // if the array is not initialized i seem toget an error
theDB.personTable
.orderBy('f_lastName')
.each((personOBJ) => {
this.thePersonArray.push(personOBJ)
console.log(" inside: ", this.thePersonArray)
}).then(() => {
// Transaction committed.
console.log(" People: Transaction committed")
}).catch(err => {
// Transaction aborted.
console.log(" People: Transaction aborted")
})
console.log(" after done: ", this.thePersonArray)
}
}, // end methods
} // end export
</script>```
I'd love some help. I'm completely stuck.
[1]: https://entrypaws.com/
Try making thePersonArray reactive by using ref
data() {
return {
thePersonArray: ref([]),
}
},
then assign the new array to thePersonArray.value
getTheUsers() {
this.thePersonArray.value = []
I think you might be able to push directly with thePersonArray as I think Vue maps/ wraps/ proxies these methods (whatever they call it :) ), so try
this.thePersonArray.push({f_lastName: "Dreamer"})
and if that doesnt work try
this.thePersonArray.value.push({f_lastName: "Dreamer"})
but I think the first will work

JSON multiple alias names angular 8

I have below interface.
interface ProductJson {
id: number;
name: string;
price: number;
}
I want to have multiple alias names for price, like price and alias names: rate, etc. How can I read json data attribute 'rate' for 'price' and also read 'price' too.
You can use a custom serializer to create aliases between fields:
Example using #kaiu/serializer:
class ProductJson {
id: number;
name: string;
#FieldName('rate')
price: number;
}
Or you can also create a getter method and use the serializert to map your JSON to a class instance in order to use your method directly, see https://kaiu-lab.github.io/serializer/ for in-depth stuff.
One way is to maintain a group of attribute names that you want to alias.
And then add the interface property price to the json itself, if it contains the aliased properties like rate or amount.
Now you can simply access price from else where, which should give the same value
Ex:
var price_group = ['price', 'rate', 'amount'];
var some_other_group = []
var resp = {rate: 200, p: 12}
var resp2 = {price: 300, p: 12};
Object.keys(resp).forEach(key => {
if(price_group.indexOf(key) > -1){
resp.price = resp[key]
}
});
console.log(resp.price)
Object.keys(resp2).forEach(key => {
if(price_group.indexOf(key) > -1){
resp.price = resp[key]
}
});
console.log(resp2.price)
I'm not sure you can do that tbh.
You can easily do it by programming your stuff that reads/writes the json to accept stuff like rate, price, moolah and just write it as
{
price: number
}
edit: what i'm saying is you take the user input or any other input that specifies something like {moolah: 30} and you take that '30' and put it on {price: 30} in your json.

Want to add extra key in mongoose records while making json in nodejs

var commentSchema = new Schema({
text: String,
actions:[{actionid:String, actiondata:String}],
author: String
})
While fetching the records, i need count for action = 1. And i want to add the count as a extra key in each comment as below:
{
"comments":[
{"commentData":{
"text":"temp1",
"author":"tempauthor1",
"actioncount":"2"
}},
{"commentData":{
"text":"temp1",
"author":"tempauthor2",
"actioncount":"3"
}}
]}
I need json response like this. Please help.
To filter only actionid = 1 and the count of actionid=1. Please try to do it through aggregation
Comment.aggregate([{$unwind: '$actions'},
// filter the actionid is 1
{$match: {'actions.actionid': '1'}},
//
{$group: {_id: 'actions.actionid',
actioncount: {$sum: 1}
}}
])

Laravel: How do I parse this json data in view blade?

Currently this is my view
{{ $leads }}
And this is the output
{"error":false,"member":[{"id":"1","firstName":"first","lastName":"last","phoneNumber":"0987654321","email":"email#yahoo.com","owner":{
"id":"10","firstName":"first","lastName":"last"}}]}
I wanted to display something like this
Member ID: 1
Firstname: First
Lastname: Last
Phone: 0987654321
Owner ID: 10
Firstname: First
Lastname: Last
It's pretty easy.
First of all send to the view decoded variable (see Laravel Views):
view('your-view')->with('leads', json_decode($leads, true));
Then just use common blade constructions (see Laravel Templating):
#foreach($leads['member'] as $member)
Member ID: {{ $member['id'] }}
Firstname: {{ $member['firstName'] }}
Lastname: {{ $member['lastName'] }}
Phone: {{ $member['phoneNumber'] }}
Owner ID: {{ $member['owner']['id'] }}
Firstname: {{ $member['owner']['firstName'] }}
Lastname: {{ $member['owner']['lastName'] }}
#endforeach
it seems you can use #json($leads) since laravel 5.5
https://laravel.com/docs/5.5/blade
For such case, you can do like this
#foreach (json_decode($leads->member) as $member)
{{ $genre }}
#endforeach
You can use json decode then you get php array,and use that value as your own way
<?php
$leads = json_decode($leads, true);
dd($leads);
The catch all for me is taking an object, encoding it, and then passing the string into a javascript script tag. To do this you have to do some replacements.
First replace every \ with a double slash \\ and then every quote" with a \".
$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
->with('payload', $payload)
Then in the blade template
#if(isset($payload))
<script>
window.__payload = JSON.parse("{!!$payload!!}");
</script>
#endif
This basically allows you to take an object on the php side, and then have an object on the javascript side.
in controller just convert json data to object using json_decode php function like this
$member = json_decode($json_string);
and pass to view in view
return view('page',compact('$member'))
in view blade
Member ID: {{$member->member[0]->id}}
Firstname: {{$member->member[0]->firstname}}
Lastname: {{$member->member[0]->lastname}}
Phone: {{$member->member[0]->phone}}
Owner ID: {{$member->owner[0]->id}}
Firstname: {{$member->owner[0]->firstname}}
Lastname: {{$member->owner[0]->lastname}}
Example if you have array format like this:
$member = [
[ "firs_name" => "Monica",
"last_name" => "Dev",
"sex" => "F"
],
[ "firs_name" => "Blake",
"last_name" => "Devante",
"sex" => "M"
],
[ "firs_name" => "Johnny",
"last_name" => "Merritt",
"sex" => "M"
]
]
You can use #json Blade directive for Laravel 5.5 to 9.x
<script>
var app = #json($member);
</script>
From Laravel 8.x to latest version you can use Illuminate\Support\Js::from method directive.
<script>
var app = {{ Illuminate\Support\Js::from($member) }};
</script>
And for short with Js facade
<script>
var app = {{ Js::from($array) }};
</script>
Reference:
https://laravel.com/docs/blade
If your data is coming from a model you can do:
App\Http\Controller\SomeController
public function index(MyModel $model)
{
return view('index', [
'data' => $model->all()->toJson(),
]);
}
index.blade.php
#push('footer-scripts')
<script>
(function(global){
var data = {!! $data !!};
console.log(data);
// [{..}]
})(window);
</script>
#endpush
Just Remove $ in to compact method ,
return view('page',compact('member'))