I'm working with twig for render data.
Here is my code:
function addProduct(product_id, product_image, product_name) {
product_ids.push(parseInt(product_id));
// console.log(file_id);
$.each(product_ids, function (i, val) {
products[i]= {id: product_id, image: product_image, name: product_name};
})
console.log(products);
$("#search-pop").slideUp();
$(".list-selected-product").append(
{% include '_layout/include/_render_product_select.html.twig' with {'products': products} %}
);
// console.log($(".list-selected-product").html(products));
}
Now i want to render_product_select but i don't know how can transmission products to this.
Please help me!
Thank so much.
Related
I'm trying to use an API for the first time. Here is how I currently call it :
url = 'https://data.economie.gouv.fr/api/records/1.0/search/?dataset=prix-carburants-fichier-instantane-test-ods-copie&q=aire+sur+l%27adour&lang=fr&facet=id&facet=adresse&facet=ville&facet=prix_maj&facet=prix_nom&facet=com_arm_name&facet=epci_name&facet=dep_name&facet=reg_name&facet=services_service&facet=horaires_automate_24_24&refine.ville=Aire-sur-l%27Adour';
datas = [];
constructor(private http: HttpClient){
this.http.get(this.url).toPromise().then((data: any) => {
this.datas = data
})
}
And HTML :
<pre class="text-white">
{{ datas | json }}
</pre>
The result shows a JSON like this :
Now, how do I access it? I already tried things like :
let data of datas :
data.records
data[0][records]
etc
Here an example, where json property rappresents your entire object:
<span *ngFor="let element of json.records">
{{element.datasetid }}
{{element.geometry }}
{{element.recordid }}
</span>
Here, Please try to create a new method and use async/await.
Create a new method something like this -
public async getData()
{
await this.http.get(this.URL)
.toPromise()
.then(response => this.datas = response['records'])
.catch(err => { console.log ('error');
});
}
Now, You can call this method from your constructor something like this -
constructor(private http: HttpClient) {
this.getData()
}
Now, You should use *ngFor directive to iterate over the datas as it is an array so you can use this data to develop HTML.
<div *ngFor="let data of datas">
{{data?.fields?.id}}
</div>
In this way, you can use this .
let me know if you need any further help on this .
please find the working link of stackblitz- https://stackblitz.com/edit/angular-dukmlc?file=src/app/app.component.ts
Thank you.
I am using twig as below
res.render("screen/index.twig", {
name: 'word',
columns: columns,
});
It is working as excepted.
Now I want to switch to twing and used below code
const contents = await twing
.render("screen/index.twig", {
name: 'word',
columns: columns,
})
res.end(contents);
here contents give below
...
<script>
window.COLUMNS = [{"alignment":"left"}];
</script>
...
But I need the below output without using any .replace function. How can I achieve this? Can anyone tell why it working in twig and not in twing? Thanks.
...
<script>
window.COLUMNS = [{"alignment":"left"}];
</script>
...
I want to include some template and append on button click (by js), and I need each included template to have a unique id.
Here is the logic where I appending the templates:
<button type="submit" id="addTranslationFields">Add translations</button>
// and js
$('#addTranslationFields').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
let part = `{% include 'translationPart.twig' with {'languages': languages,}%}`;
$('.table tbody').append(part);
});
Here is the how I generate uuid in the translationPart.twig
{% set uuid = uuid() %}
{{ uuid }}
The issue is that UUID is the same for all of the created templates. I understand why it's happening, it's b-z twig generated server-side and at the moment of generation it sees only one include. But is there some option to rerender included template for each new included copy? Or maybe some other way to set different UUIDs for each of the included templates.
Updated
uuid() is a custom twig function
$twig->addFunction(
new TwigFunction(
'uuid',
static function(): string {
return Uuid::uuid4()->toString();
}
)
);
You can achieve this via ajax calls, or string replacement.
String replacement
Twig template (translationPart.twig)
{% set uuid = '#_SOME_STRING_TO_REPLACE_#' %}
{{ uuid }}
Javascript
<button type="submit" id="addTranslationFields">Add translations</button>
// and js
$('#addTranslationFields').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
let generatedUuid = generateUuidByJavascript();
let part = `{% include 'translationPart.twig' with {'languages': languages,}%}`.replace('#_SOME_STRING_TO_REPLACE_#', generatedUuid);
$('.table tbody').append(part);
});
Uuidjs can be used for generating uuid.
I have a list of items where the title is a link to display a detailed view of the item. Click the title and it correctly goes to url + Id. In the Vue tolls the detail page retrieves the item with matching ID but as and array not an object and the template does not display any properties - what am I missing?
<script>
import axios from "axios";
export default {
name: "Report",
data() {
return {
report: {}
};
},
mounted: function() {
this.getReport();
},
methods: {
getReport() {
let uri = "http://localhost:5000/api/reports/" + this.$route.params.id;
axios.get(uri).then(response => {
this.report = response.data;
});
}
}
};
</script>
The template is so
<template>
<v-content>
<h1>report detail page</h1>
<p>content will go here</p>-
<h3>{{ report.month }}</h3>
<pre>{{ report._id }}</pre>
</v-content>
</template>
any comments appreciated
url + Id
It sounds like your issue is that you are receiving an array not an object.
You can pull out objects encapsulated inside arrays easily.
For example, if we had the following data:
var bus1 = {passengers:10, shift:1}
var busArr = [bus1]
which we can assert: busArr === [{passengers:10, shift:1}]
We could then pull out bus1 by referencing the index 0:
var bus1New = busArr[0]
If you want to avoid the data transformation and just output the structure you can consider a v-for in your template.
<p v-for="val in report">
_id: {{val._id}}
<br>
month: {{val.month}}
</p>
I have a layout Jade view that has a menu via unordered list, and I want to set the <li> to be <li class="active">...</li> when the current page is rendered in the browser.
I assume I will have to access the current request to determine when to set the attribute on the <li>
I can't find any examples of how to do this so hoping someone can help
Thanks
Try this before your call res.render() in your route:
res.locals.path = req.path;
res.render('/page');
or
res.render('/page', { path: req.path });
Then you would have to do a bunch of if/else statements in your view (as the above solution suggests).
- if(currentUrl === '/')
li(class='active')
a(href='/') Current Driver Standings
- else
li
a(href='/') Current Driver Standings
I however, prefer to do this on client side instead, to keep my template files free from as much logic as possible:
In page template file (this is ejs, not sure how to echo in jade):
<body data-path="<%= path %>">
Then with jQuery you can grab the path from body and attach an active class:
$(function(){
var path = $('body').attr('data-path');
$('nav li a[href='+path+']').parents('li').addClass('active');
});
Update: You can also just use var path = window.location.pathname instead of saving it to an attribute on body
//no need to save path to <body> tag first:
$(function(){
var path = window.location.pathname;
$('nav li a[href='+path+']').parents('li').addClass('active');
});
Here's a much neater way of doing it, server-side:
In your routes.js (or wherever) define an array of objects representing your nav like such:
var navLinks = [
{ label: 'Home', key: 'home', path: '' },
{ label: 'About', key: 'about', path: '/about' },
{ label: 'Contact', key: 'contact', path: '/contact' }
]
Pass the navLinks variable to your view, as well as the key of the item you'd like hilighted:
res.render('home', { title: 'Welcome!', section: 'home', navLinks: navLinks });
You can also add the navLinks variable to app.locals and save yourself always having to provide it explicitly to views.
Then in your jade template loop through the array of links and set the active class on the one whose key matches the provided section:
ul(class='nav nav-list')
- navLinks.forEach(function(link){
- var isActive = (link.key == section ? 'active' : '')
li(class=isActive)
a(href=link.path)= link.label
- })
Pass the req.originalUrl in your routes file. example: in your
/routes/about.js
router.get('/', function(req, res) {
res.render('about', {
url: req.originalUrl
});
});
Then, write if else condition on your jade template
if(url==='/about-us')
li(class='active')
a(href='about-us') About Us
else
li
a(href='about-us') About Us
you can use global variables in app.js like :
// Global vars
app.use( function ( req, res, next ) {
// rest of your code ...
res.locals.current_url = req.path;
// rest of your code ...
next();
} );
// then in your .jade file:
ul.navbar-nav.mr-auto
li(class="nav-item #{ current_url === '/page1' ? 'active' : ''}")
a.nav-link(href='/page1') Page1
like this you are able to use "current_url" globally all around your view files
I came up with this which works however I'm not sure if its best practice. Please let me know either way:
response.render("current/currentSchedule", {
title: "Current Race Schedule",
currentUrl: req.path,
});
ul(class='nav nav-list')
li(class='nav-header') Current Season
- if(currentUrl === '/')
li(class='active')
a(href='/') Current Driver Standings
- else
li
a(href='/') Current Driver Standings
- if(currentUrl === '/constructor-standings')
li(class='active')
a(href='/constructor-standings') Current Constructor Standings
- else
li
a(href='/constructor-standings') Current Constructor Standings
- if(currentUrl === '/current-schedule')
li(class='active')
a(href='/current-schedule') Current Race Schedule
- else
li
a(href='/current-schedule') Current Race Schedule