Explore all Template Engine open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Template Engine

No Popular Releases are available at this moment for Template Engine

Popular Libraries in Template Engine

No Trending Libraries are available at this moment for Template Engine

Trending New libraries in Template Engine

No Trending Libraries are available at this moment for Template Engine

Top Authors in Template Engine

No Top Authors are available at this moment for Template Engine.

Trending Kits in Template Engine

No Trending Kits are available at this moment for Template Engine

Trending Discussions on Template Engine

How to create a no refresh page using jquery, express and handlebars?

Adding external javascript snippet to a Wagtail page field

Trying to connect to prismic got "getFirst is not a function"

How to change var type to integer?

Button not working properly - Java Spring Thymeleaf

ANTLR: how to debug a misidentified token

Ninja Framework: Can we really use Mustache template engine instead of FreeMarker?

Spring MVC Integration with Thymeleaf + Existing JSP apache tiles

When I'm visiting another page, The images, logos, and icons are not displayed. In this project, I'm using the pug template engine and express.js

Error while outputting template engine maximum recursion depth exceeded while calling a Python object

QUESTION

How to create a no refresh page using jquery, express and handlebars?

Asked 2022-Mar-09 at 16:25

I am learning express JS and my problem is: I want to create two pages using NodeJS, that uses handlebars as template engine, but I want that the first page should be send using res.render('home'), and the second page should be called by jQuery using ajax call to express and get the response as rendered HTML from express server, then load an about page without refreshing. I tried using the method shown in this StackOverflow question but I am not satisfied. please guide me how can i achieve it.

ANSWER

Answered 2022-Mar-09 at 16:25

so guys I finally found an answer to my question, I hope you it will help you too. Follow these steps one by one to create a no refresh website using jquery, express and handlebars. Just a tutorial for something that is combination of multiple things.

1. Create a folder name mywebsite

2. run npm init and install the following dependencies

1    "express-handlebars": "^5.3.4",
2    "handlebars": "^4.7.7",
3    "hbs": "^4.1.2"
4

3. Now create a main.js file with the following code

1    "express-handlebars": "^5.3.4",
2    "handlebars": "^4.7.7",
3    "hbs": "^4.1.2"
4const express = require('express')
5const app = express();
6const static_path = __dirname + "/static"
7const hbs = require("hbs");
8
9app.set('view engine', 'hbs');
10app.set("views", __dirname + "/pages");
11
12app.use(express.static(static_path));
13
14var exhb = require('express-handlebars').create();
15
16app.get("/", (req, res) => {
17    res.render('index', { title: "Home Test", pagename: "This is my Home page" });
18});
19
20app.get('/getabout', (req, res) => {
21    exhb.render("pages/about.hbs", { title: "About US page", body: "Body" }).then((html) => {
22        res.send({ data: html });
23    }).catch((err) => {
24        console.log(err);
25    })
26});
27
28app.listen(8080, 'localhost', () => {
29    console.log("listening at http://localhost:8080")
30})
31

4. Now create a static folder with a file index.js and write the following code

1    "express-handlebars": "^5.3.4",
2    "handlebars": "^4.7.7",
3    "hbs": "^4.1.2"
4const express = require('express')
5const app = express();
6const static_path = __dirname + "/static"
7const hbs = require("hbs");
8
9app.set('view engine', 'hbs');
10app.set("views", __dirname + "/pages");
11
12app.use(express.static(static_path));
13
14var exhb = require('express-handlebars').create();
15
16app.get("/", (req, res) => {
17    res.render('index', { title: "Home Test", pagename: "This is my Home page" });
18});
19
20app.get('/getabout', (req, res) => {
21    exhb.render("pages/about.hbs", { title: "About US page", body: "Body" }).then((html) => {
22        res.send({ data: html });
23    }).catch((err) => {
24        console.log(err);
25    })
26});
27
28app.listen(8080, 'localhost', () => {
29    console.log("listening at http://localhost:8080")
30})
31async function callAbout() {
32    let data = await fetch('http://localhost:8080/getabout');
33    let response = await data.json();
34    console.log(response);
35    $("html").html(response['data']);
36    window.history.pushState(
37        'about us',
38        'About us',
39        '/aboutus');
40}
41

5. Now create a pages folder with two files index.hbs and about.hbs index.hbs will contain the following code

1    "express-handlebars": "^5.3.4",
2    "handlebars": "^4.7.7",
3    "hbs": "^4.1.2"
4const express = require('express')
5const app = express();
6const static_path = __dirname + "/static"
7const hbs = require("hbs");
8
9app.set('view engine', 'hbs');
10app.set("views", __dirname + "/pages");
11
12app.use(express.static(static_path));
13
14var exhb = require('express-handlebars').create();
15
16app.get("/", (req, res) => {
17    res.render('index', { title: "Home Test", pagename: "This is my Home page" });
18});
19
20app.get('/getabout', (req, res) => {
21    exhb.render("pages/about.hbs", { title: "About US page", body: "Body" }).then((html) => {
22        res.send({ data: html });
23    }).catch((err) => {
24        console.log(err);
25    })
26});
27
28app.listen(8080, 'localhost', () => {
29    console.log("listening at http://localhost:8080")
30})
31async function callAbout() {
32    let data = await fetch('http://localhost:8080/getabout');
33    let response = await data.json();
34    console.log(response);
35    $("html").html(response['data']);
36    window.history.pushState(
37        'about us',
38        'About us',
39        '/aboutus');
40}
41<!DOCTYPE html>
42<html lang="en">
43<head>
44    <meta charset="UTF-8">
45    <meta http-equiv="X-UA-Compatible" content="IE=edge">
46    <meta name="viewport" content="width=device-width, initial-scale=1.0">
47    <title>{{title}}</title>
48</head>
49<body>
50    <h1>{{pagename}}</h1>
51    Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint assumenda aliquam dolor consectetur recusandae possimus illo praesentium atque nihil exercitationem!
52    <button onclick="callAbout()">About us</button>
53
54    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
55    <script src="./index.js"></script>
56</body>
57</html>
58

about.hbs will contain the following code

1    "express-handlebars": "^5.3.4",
2    "handlebars": "^4.7.7",
3    "hbs": "^4.1.2"
4const express = require('express')
5const app = express();
6const static_path = __dirname + "/static"
7const hbs = require("hbs");
8
9app.set('view engine', 'hbs');
10app.set("views", __dirname + "/pages");
11
12app.use(express.static(static_path));
13
14var exhb = require('express-handlebars').create();
15
16app.get("/", (req, res) => {
17    res.render('index', { title: "Home Test", pagename: "This is my Home page" });
18});
19
20app.get('/getabout', (req, res) => {
21    exhb.render("pages/about.hbs", { title: "About US page", body: "Body" }).then((html) => {
22        res.send({ data: html });
23    }).catch((err) => {
24        console.log(err);
25    })
26});
27
28app.listen(8080, 'localhost', () => {
29    console.log("listening at http://localhost:8080")
30})
31async function callAbout() {
32    let data = await fetch('http://localhost:8080/getabout');
33    let response = await data.json();
34    console.log(response);
35    $("html").html(response['data']);
36    window.history.pushState(
37        'about us',
38        'About us',
39        '/aboutus');
40}
41<!DOCTYPE html>
42<html lang="en">
43<head>
44    <meta charset="UTF-8">
45    <meta http-equiv="X-UA-Compatible" content="IE=edge">
46    <meta name="viewport" content="width=device-width, initial-scale=1.0">
47    <title>{{title}}</title>
48</head>
49<body>
50    <h1>{{pagename}}</h1>
51    Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint assumenda aliquam dolor consectetur recusandae possimus illo praesentium atque nihil exercitationem!
52    <button onclick="callAbout()">About us</button>
53
54    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
55    <script src="./index.js"></script>
56</body>
57</html>
58<!DOCTYPE html>
59<html lang="en">
60
61<head>
62    <meta charset="UTF-8">
63    <meta http-equiv="X-UA-Compatible" content="IE=edge">
64    <meta name="viewport" content="width=device-width, initial-scale=1.0">
65    <title>{{title}}</title>
66</head>
67
68<body>
69<h1>This is my about us page created using NODE</h1>
70Lorem ipsum dolor, sit amet consectetur adipisicing elit. Explicabo accusamus autem accusantium suscipit, minima blanditiis ducimus quisquam fugiat, eligendi repellendus provident quasi dolores nesciunt laboriosam commodi illum repellat error eos.
71{{body}}
72</body>
73
74</html>
75

6. Now run node.js and click the About Us button and see the magic

Hope this tutorial might help anyone trying to accomplish new things

Source https://stackoverflow.com/questions/69314067

QUESTION

Adding external javascript snippet to a Wagtail page field

Asked 2022-Feb-28 at 22:44

My current Wagtail project has a very simple structure with some generic pages that have just a body RichTextField. These are just basic CMS type pages where an editor will edit some content in the rich text editor and publish.

One of the pages (and probably more in time) is a "Help Wanted" page and uses an external javascript snippet from a third-party service that lists current job openings with links to the applications that are hosted by them.

Since adding a <script> tag to the rich text editor simply escapes it and displays only the text value, I added an additional extra_scripts = models.TextField() to my page model along with a corresponding FieldPanel('extra_scripts') to the content panels. This lets a user paste in some arbitrary javascript snippets.

If I include this field value in my template with {{page.extra_scripts}} it just displays the content and does not execute the javascript. Looking through the available wagtailcore_tags I'm not seeing a filter that I should use to execute the content, and when it's used with a {{}} tag, I presume the template engine handles it so that it doesn't execute.

How can I include this field in a template so that the javascript is executed?

I know I can change the field to just be the actual javascript content without the <script> tag, but the snippet also includes some basic HTML elements, and the end users aren't going to intuitively know that they need to manually edit the provided snippet if I only give them a field to paste certain parts of the snippet. I want the end user to be able to just copy/paste the snippet they get and have it work without them needing to understand anything else.

ANSWER

Answered 2022-Feb-28 at 22:44

This is a result of the Django template language's auto-escaping behaviour, and can be overridden by adding a |safe filter:

1{{ page.extra_scripts|safe }}
2

Of course, you should only do this if your editorial users are fully trusted, since it will give them the ability to run arbitrary code (including, for example, hijacking the session cookie of a superuser who happens to visit that page).

Source https://stackoverflow.com/questions/71301680

QUESTION

Trying to connect to prismic got &quot;getFirst is not a function&quot;

Asked 2022-Feb-01 at 11:35

So I'm running an app with nodejs + express, and trying to connect to the prismic API. The documentation is using the ESM, but I want to do it using CommonJS, when I finished the config and tried to run the app, I got the error getFirst is not a function, and I am suspecting that could be in the way I declared the export client to "module.export.client". But because I am not familiar with this so I am not 100% sure.

So at the moment my app.js file looks like this

1require('dotenv').config()
2
3
4const express = require('express')
5const app = express()
6const path = require('path')
7const port = 3000
8const client = require('./config/prismicConfig.js')
9
10//Prismic
11const prismic = require('@prismicio/client')
12const prismicH = require('@prismicio/helpers')
13const fetch = require('node-fetch')
14
15
16const repoName = 'my-repo-name'
17const accessToken = process.env.PRISMIC_ACCESS_TOKEN 
18const endpoint = prismic.getEndpoint(repoName) 
19
20const routes = [
21    {
22        type:'page',
23        path:'/'
24    }
25]
26
27module.exports.client =  prismic.createClient(endpoint, { 
28    fetch, 
29    accessToken,
30    routes,
31  })
32
33//Prismic
34
35
36
37//  template engine
38app.set('views', path.join(__dirname,'views'))
39app.set('view engine', 'pug')
40
41
42
43//Middleware
44app.use((req, res, next) =&gt; {
45    res.locals.ctx = {
46      prismicH,
47    }
48    next()
49  })
50  //end
51
52
53
54app.get('/', async (req, res) =&gt; {
55
56  const document = await client.getFirst()
57  res.render('page', { document })
58
59})
60
61app.listen(port, ()=&gt;{
62    console.log(` Example listen to http://localhost:${port}`)
63})
64
65

And this is my prismicConfig.js

1require('dotenv').config()
2
3
4const express = require('express')
5const app = express()
6const path = require('path')
7const port = 3000
8const client = require('./config/prismicConfig.js')
9
10//Prismic
11const prismic = require('@prismicio/client')
12const prismicH = require('@prismicio/helpers')
13const fetch = require('node-fetch')
14
15
16const repoName = 'my-repo-name'
17const accessToken = process.env.PRISMIC_ACCESS_TOKEN 
18const endpoint = prismic.getEndpoint(repoName) 
19
20const routes = [
21    {
22        type:'page',
23        path:'/'
24    }
25]
26
27module.exports.client =  prismic.createClient(endpoint, { 
28    fetch, 
29    accessToken,
30    routes,
31  })
32
33//Prismic
34
35
36
37//  template engine
38app.set('views', path.join(__dirname,'views'))
39app.set('view engine', 'pug')
40
41
42
43//Middleware
44app.use((req, res, next) =&gt; {
45    res.locals.ctx = {
46      prismicH,
47    }
48    next()
49  })
50  //end
51
52
53
54app.get('/', async (req, res) =&gt; {
55
56  const document = await client.getFirst()
57  res.render('page', { document })
58
59})
60
61app.listen(port, ()=&gt;{
62    console.log(` Example listen to http://localhost:${port}`)
63})
64
65
66require('dotenv').config()
67console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
68
69const fetch = require ('node-fetch')
70const prismic = require ('@prismicio/client')
71
72const repoName = 'my-repo-name' 
73const accessToken = process.env.PRISMIC_ACCESS_TOKEN 
74const endpoint = prismic.getEndpoint(repoName) 
75
76
77const routes = [
78  {
79    type: 'page',
80    path: '/',
81  },
82]
83
84module.exports.client = prismic.createClient(endpoint, { 
85  fetch, 
86  accessToken,
87  routes,
88})
89

So I will appreciate an advice on this. In advance thank you for reading me :)

ANSWER

Answered 2022-Feb-01 at 11:35

it's client.client then, so you should require it like so:

1require('dotenv').config()
2
3
4const express = require('express')
5const app = express()
6const path = require('path')
7const port = 3000
8const client = require('./config/prismicConfig.js')
9
10//Prismic
11const prismic = require('@prismicio/client')
12const prismicH = require('@prismicio/helpers')
13const fetch = require('node-fetch')
14
15
16const repoName = 'my-repo-name'
17const accessToken = process.env.PRISMIC_ACCESS_TOKEN 
18const endpoint = prismic.getEndpoint(repoName) 
19
20const routes = [
21    {
22        type:'page',
23        path:'/'
24    }
25]
26
27module.exports.client =  prismic.createClient(endpoint, { 
28    fetch, 
29    accessToken,
30    routes,
31  })
32
33//Prismic
34
35
36
37//  template engine
38app.set('views', path.join(__dirname,'views'))
39app.set('view engine', 'pug')
40
41
42
43//Middleware
44app.use((req, res, next) =&gt; {
45    res.locals.ctx = {
46      prismicH,
47    }
48    next()
49  })
50  //end
51
52
53
54app.get('/', async (req, res) =&gt; {
55
56  const document = await client.getFirst()
57  res.render('page', { document })
58
59})
60
61app.listen(port, ()=&gt;{
62    console.log(` Example listen to http://localhost:${port}`)
63})
64
65
66require('dotenv').config()
67console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
68
69const fetch = require ('node-fetch')
70const prismic = require ('@prismicio/client')
71
72const repoName = 'my-repo-name' 
73const accessToken = process.env.PRISMIC_ACCESS_TOKEN 
74const endpoint = prismic.getEndpoint(repoName) 
75
76
77const routes = [
78  {
79    type: 'page',
80    path: '/',
81  },
82]
83
84module.exports.client = prismic.createClient(endpoint, { 
85  fetch, 
86  accessToken,
87  routes,
88})
89const {client} = require('./config/prismicConfig.js')
90

also, you don't need prismic setup in the server/app.js, as it's in the config already:

try changing app.js like so:

1require('dotenv').config()
2
3
4const express = require('express')
5const app = express()
6const path = require('path')
7const port = 3000
8const client = require('./config/prismicConfig.js')
9
10//Prismic
11const prismic = require('@prismicio/client')
12const prismicH = require('@prismicio/helpers')
13const fetch = require('node-fetch')
14
15
16const repoName = 'my-repo-name'
17const accessToken = process.env.PRISMIC_ACCESS_TOKEN 
18const endpoint = prismic.getEndpoint(repoName) 
19
20const routes = [
21    {
22        type:'page',
23        path:'/'
24    }
25]
26
27module.exports.client =  prismic.createClient(endpoint, { 
28    fetch, 
29    accessToken,
30    routes,
31  })
32
33//Prismic
34
35
36
37//  template engine
38app.set('views', path.join(__dirname,'views'))
39app.set('view engine', 'pug')
40
41
42
43//Middleware
44app.use((req, res, next) =&gt; {
45    res.locals.ctx = {
46      prismicH,
47    }
48    next()
49  })
50  //end
51
52
53
54app.get('/', async (req, res) =&gt; {
55
56  const document = await client.getFirst()
57  res.render('page', { document })
58
59})
60
61app.listen(port, ()=&gt;{
62    console.log(` Example listen to http://localhost:${port}`)
63})
64
65
66require('dotenv').config()
67console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
68
69const fetch = require ('node-fetch')
70const prismic = require ('@prismicio/client')
71
72const repoName = 'my-repo-name' 
73const accessToken = process.env.PRISMIC_ACCESS_TOKEN 
74const endpoint = prismic.getEndpoint(repoName) 
75
76
77const routes = [
78  {
79    type: 'page',
80    path: '/',
81  },
82]
83
84module.exports.client = prismic.createClient(endpoint, { 
85  fetch, 
86  accessToken,
87  routes,
88})
89const {client} = require('./config/prismicConfig.js')
90require('dotenv').config()
91
92
93const express = require('express')
94const app = express()
95const path = require('path')
96const port = 3000
97const prismicH = require('@prismicio/helpers')
98const {client} = require('./config/prismicConfig.js')
99
100
101//  template engine
102app.set('views', path.join(__dirname,'views'))
103app.set('view engine', 'pug')
104
105
106
107//Middleware
108app.use((req, res, next) =&gt; {
109    res.locals.ctx = {
110      prismicH,
111    }
112    next()
113  })
114  //end
115
116
117
118app.get('/', async (req, res) =&gt; {
119
120  const document = await client.getFirst()
121  res.render('page', { document })
122
123})
124
125app.listen(port, ()=&gt;{
126    console.log(` Example listen to http://localhost:${port}`)
127})
128

Source https://stackoverflow.com/questions/70938991

QUESTION

How to change var type to integer?

Asked 2022-Jan-20 at 14:41

I am reading from a CSV file, register a variable and loop through the variable's list. It's as easy as below example:

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33

Now let's get into the issue. When triggering the last task, integers are required for an_integer and another_integer. Otherwise the API below will fail.

The problem: the Jinja2 template engine will ALWAYS return a string. an_integer: "{{ item.val | int }}", for example, won't change that behavior.

As you can see from the output of task 3 (debug), the values are already string when read from csv / registered.

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47

How can I force a module parameter to be set as integer?

ANSWER

Answered 2022-Jan-20 at 13:07

The items on the list are strings. For example

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47    - debug:
48        msg: |
49          vms.list.0.val: {{ vms.list.0.val }} {{ vms.list.0.val|type_debug }}
50

gives (Use yaml callback plugin. See shell> ansible-doc -t callback yaml)

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47    - debug:
48        msg: |
49          vms.list.0.val: {{ vms.list.0.val }} {{ vms.list.0.val|type_debug }}
50  msg: |-
51    vms.list.0.val: 1 AnsibleUnicode
52

Convert the items of the list to integers. Create the list first, e.g.

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47    - debug:
48        msg: |
49          vms.list.0.val: {{ vms.list.0.val }} {{ vms.list.0.val|type_debug }}
50  msg: |-
51    vms.list.0.val: 1 AnsibleUnicode
52    - set_fact:
53        _list: &quot;{{ _list|d([]) + [item|combine(_item)] }}&quot;
54      loop: &quot;{{ vms.list }}&quot;
55      vars:
56        _item: &quot;{{ {'ues': item.ues|int, 'val': item.val|int} }}&quot;
57

gives

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47    - debug:
48        msg: |
49          vms.list.0.val: {{ vms.list.0.val }} {{ vms.list.0.val|type_debug }}
50  msg: |-
51    vms.list.0.val: 1 AnsibleUnicode
52    - set_fact:
53        _list: &quot;{{ _list|d([]) + [item|combine(_item)] }}&quot;
54      loop: &quot;{{ vms.list }}&quot;
55      vars:
56        _item: &quot;{{ {'ues': item.ues|int, 'val': item.val|int} }}&quot;
57  _list:
58  - some: string
59    ues: 2
60    val: 1
61

Then update the list in the dictionary

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47    - debug:
48        msg: |
49          vms.list.0.val: {{ vms.list.0.val }} {{ vms.list.0.val|type_debug }}
50  msg: |-
51    vms.list.0.val: 1 AnsibleUnicode
52    - set_fact:
53        _list: &quot;{{ _list|d([]) + [item|combine(_item)] }}&quot;
54      loop: &quot;{{ vms.list }}&quot;
55      vars:
56        _item: &quot;{{ {'ues': item.ues|int, 'val': item.val|int} }}&quot;
57  _list:
58  - some: string
59    ues: 2
60    val: 1
61    - set_fact:
62        vms: &quot;{{ vms|combine({'list': _list}) }}&quot;
63

gives

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47    - debug:
48        msg: |
49          vms.list.0.val: {{ vms.list.0.val }} {{ vms.list.0.val|type_debug }}
50  msg: |-
51    vms.list.0.val: 1 AnsibleUnicode
52    - set_fact:
53        _list: &quot;{{ _list|d([]) + [item|combine(_item)] }}&quot;
54      loop: &quot;{{ vms.list }}&quot;
55      vars:
56        _item: &quot;{{ {'ues': item.ues|int, 'val': item.val|int} }}&quot;
57  _list:
58  - some: string
59    ues: 2
60    val: 1
61    - set_fact:
62        vms: &quot;{{ vms|combine({'list': _list}) }}&quot;
63  vms:
64    changed: false
65    dict: {}
66    failed: false
67    list:
68    - some: string
69      ues: 2
70      val: 1
71

The debug task will show the type is integer now

1---
2- hosts: localhost
3  vars:
4    csv: |
5      some;val;ues
6      string;1;2
7  tasks:
8        
9    - name: copy
10      copy:
11        content: &quot;{{csv}}&quot;
12        dest: &quot;vm.csv&quot;
13        
14    - name: read csv
15      community.general.read_csv:
16        path: &quot;vm.csv&quot;
17        delimiter: &quot;;&quot;
18      register: vms
19        
20    - name: debug
21      debug:
22        var: vms
23
24    - name: Trigger AWX
25      awx.awx.workflow_launch:
26        name: &quot;Do the job!&quot;
27        extra_vars:
28          some_string: &quot;{{ item.some }}&quot;
29          an_integer: &quot;{{ item.val }}&quot;
30          another_integer: &quot;{{ item.ues }}&quot;
31      with_items: &quot;{{ vms.list }}&quot;
32
33ok: [localhost] =&gt; {
34    &quot;vms&quot;: {
35        &quot;changed&quot;: false,
36        &quot;dict&quot;: {},
37        &quot;failed&quot;: false,
38        &quot;list&quot;: [
39            {
40                &quot;some&quot;: &quot;string&quot;,
41                &quot;ues&quot;: &quot;2&quot;,
42                &quot;val&quot;: &quot;1&quot;
43            }
44        ]
45    }
46}
47    - debug:
48        msg: |
49          vms.list.0.val: {{ vms.list.0.val }} {{ vms.list.0.val|type_debug }}
50  msg: |-
51    vms.list.0.val: 1 AnsibleUnicode
52    - set_fact:
53        _list: &quot;{{ _list|d([]) + [item|combine(_item)] }}&quot;
54      loop: &quot;{{ vms.list }}&quot;
55      vars:
56        _item: &quot;{{ {'ues': item.ues|int, 'val': item.val|int} }}&quot;
57  _list:
58  - some: string
59    ues: 2
60    val: 1
61    - set_fact:
62        vms: &quot;{{ vms|combine({'list': _list}) }}&quot;
63  vms:
64    changed: false
65    dict: {}
66    failed: false
67    list:
68    - some: string
69      ues: 2
70      val: 1
71  msg: |-
72    vms.list.0.val: 1 int
73

Source https://stackoverflow.com/questions/70785828

QUESTION

Button not working properly - Java Spring Thymeleaf

Asked 2021-Dec-21 at 13:29

I am writing a simple web application with CRUD operations using Thymeleaf as a template engine. The problem is, this is my code:

1&lt;form th:method=&quot;POST&quot; th:action=&quot;@{/}&quot;&gt;
2    &lt;div&gt;
3       &lt;ul th:each=&quot;balloon: ${balloons}&quot; style=&quot;list-style-type: none&quot;&gt;
4          &lt;li&gt;
5             &lt;input type=&quot;radio&quot; name=&quot;balloonType&quot; th:text=&quot;${balloon.getName()}&quot;
6                    th:value=&quot;${balloon.getDescription()}&quot;&gt;
7          &lt;/li&gt;
8
9          &lt;div&gt;
10             &lt;form th:method=&quot;POST&quot; th:action=&quot;@{'/balloons/delete/{id}' (id=${balloon.getId()})}&quot;&gt;
11                 &lt;input type=&quot;submit&quot; value=&quot;Delete&quot;&gt;
12             &lt;/form&gt;
13          &lt;/div&gt;
14
15       &lt;/ul&gt;
16       &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
17    &lt;/div&gt;
18    &lt;br/&gt;
19&lt;/form&gt;
20

and when I run the application, the code in the inspect element is shown in the picture below. The first delete button does not appear in its own form and therefore does not work properly. Any help is welcome.

enter image description here

ANSWER

Answered 2021-Dec-21 at 13:29

You can not and should not have nested form tags. Its a bad practice. I would say you separate them out like below:

1&lt;form th:method=&quot;POST&quot; th:action=&quot;@{/}&quot;&gt;
2    &lt;div&gt;
3       &lt;ul th:each=&quot;balloon: ${balloons}&quot; style=&quot;list-style-type: none&quot;&gt;
4          &lt;li&gt;
5             &lt;input type=&quot;radio&quot; name=&quot;balloonType&quot; th:text=&quot;${balloon.getName()}&quot;
6                    th:value=&quot;${balloon.getDescription()}&quot;&gt;
7          &lt;/li&gt;
8
9          &lt;div&gt;
10             &lt;form th:method=&quot;POST&quot; th:action=&quot;@{'/balloons/delete/{id}' (id=${balloon.getId()})}&quot;&gt;
11                 &lt;input type=&quot;submit&quot; value=&quot;Delete&quot;&gt;
12             &lt;/form&gt;
13          &lt;/div&gt;
14
15       &lt;/ul&gt;
16       &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
17    &lt;/div&gt;
18    &lt;br/&gt;
19&lt;/form&gt;
20&lt;form action=&quot;/form1action1&quot;...&gt;
21
22&lt;/form&gt;
23
24&lt;form action=&quot;/form2action2&quot;...&gt;
25
26&lt;/form&gt;
27

If you must take some action within the form, introduce some JavaScript (or ajax or jQuery, if you prefer) snippets.

Source https://stackoverflow.com/questions/70435626

QUESTION

ANTLR: how to debug a misidentified token

Asked 2021-Dec-20 at 21:35

I am trying to implement a grammar in Antlr4 for a simple template engine. This engine consists of 3 different clauses:

IF ANSWERED ( variable )

END IF

Variable

Variable can be any upper or lowercase letter including white spaces. Both IF ANSWERED and END IF are always uppercase.

I have written the following grammar/lexer rules so far, but my problem is that IF ANSWERED keeps getting recognized as a Variable and not as 2 tokens IF and ANSWERED.

1grammar program;
2
3/**grammar */
4command: (ifStart | ifEnd | VARIABLE ) EOF;
5
6ifStart: IF ANSWERED '(' VARIABLE ')';
7
8ifEnd: 'END IF';
9
10/** lexer */
11
12IF: 'IF';
13ANSWERED: 'ANSWERED';
14
15TEXT: (LOWERCASE | UPPERCASE | NUMBER) ;
16VARIABLE: (TEXT | [ \t\r\n])+;
17
18fragment LOWERCASE: [a-z];
19fragment UPPERCASE: [A-Z];
20fragment NUMBER: [0-9];
21

If I try to parse IF ANSWERED ( FirstName ) I get the following output:

1grammar program;
2
3/**grammar */
4command: (ifStart | ifEnd | VARIABLE ) EOF;
5
6ifStart: IF ANSWERED '(' VARIABLE ')';
7
8ifEnd: 'END IF';
9
10/** lexer */
11
12IF: 'IF';
13ANSWERED: 'ANSWERED';
14
15TEXT: (LOWERCASE | UPPERCASE | NUMBER) ;
16VARIABLE: (TEXT | [ \t\r\n])+;
17
18fragment LOWERCASE: [a-z];
19fragment UPPERCASE: [A-Z];
20fragment NUMBER: [0-9];
21[@0,0:10='IF ANSWERED',**&lt;VARIABLE&gt;**,1:0]
22[@1,11:11='(',&lt;'('&gt;,1:11]
23[@2,12:25='Execution date',&lt;VARIABLE&gt;,1:12]
24[@3,26:26=')',&lt;')'&gt;,1:26]
25[@4,27:26='&lt;EOF&gt;',&lt;EOF&gt;,1:27]
26line 1:0 mismatched input 'IF ANSWERED' expecting 'IF'
27

I read that Antlr4 is greedy and tries to match the biggest possible token, but I fail to understand what is the correct approach, or how to think through the problem to find a solution.

ANSWER

Answered 2021-Dec-20 at 21:35

Correct: ANTLR's lexer is greedy, and tries to consume as much as possible. That is why IF ANSWERED is tokenised as a TEXT token instead of 2 separate keywords. You'll need to change TEXT so that it does not match spaces.

Something like this could get you started:

1grammar program;
2
3/**grammar */
4command: (ifStart | ifEnd | VARIABLE ) EOF;
5
6ifStart: IF ANSWERED '(' VARIABLE ')';
7
8ifEnd: 'END IF';
9
10/** lexer */
11
12IF: 'IF';
13ANSWERED: 'ANSWERED';
14
15TEXT: (LOWERCASE | UPPERCASE | NUMBER) ;
16VARIABLE: (TEXT | [ \t\r\n])+;
17
18fragment LOWERCASE: [a-z];
19fragment UPPERCASE: [A-Z];
20fragment NUMBER: [0-9];
21[@0,0:10='IF ANSWERED',**&lt;VARIABLE&gt;**,1:0]
22[@1,11:11='(',&lt;'('&gt;,1:11]
23[@2,12:25='Execution date',&lt;VARIABLE&gt;,1:12]
24[@3,26:26=')',&lt;')'&gt;,1:26]
25[@4,27:26='&lt;EOF&gt;',&lt;EOF&gt;,1:27]
26line 1:0 mismatched input 'IF ANSWERED' expecting 'IF'
27parse
28 : command* EOF
29 ;
30
31command
32 : (ifStatement | variable)+
33 ;
34
35ifStatement
36 : IF ANSWERED '(' variable ')' command* END IF
37 ;
38
39variable
40 : TEXT
41 ;
42
43IF       : 'IF';
44END      : 'END';
45ANSWERED : 'ANSWERED';
46TEXT     : [a-zA-Z0-9]+;
47SPACES   : [ \t\r\n]+ -&gt; skip;
48

Source https://stackoverflow.com/questions/70428170

QUESTION

Ninja Framework: Can we really use Mustache template engine instead of FreeMarker?

Asked 2021-Dec-13 at 10:03

The official page(https://www.ninjaframework.org/documentation/modules.html) mentions Mustache template engine and its referenced page(https://github.com/kpacha/ninja-mustache) seems to say that Mustache template engine can be used. Is it true?

We added the following dependency to our pom.xml, but the Eclipse reported an error at the first line of this dependency in the pom.xml and we couldn't build our Ninja Web application.

1&lt;dependency&gt;
2    &lt;groupId&gt;org.ninjaframework&lt;/groupId&gt;
3    &lt;artifactId&gt;ninja-mustache-module&lt;/artifactId&gt;
4    &lt;version&gt;0.1.1&lt;/version&gt;
5&lt;/dependency&gt;
6

If possible, what should we do to avoid the error and to use Mustache template engine instead of FreeMarker?

ANSWER

Answered 2021-Dec-13 at 10:03

I have checked out the project and it seeems its Maven artifact is not published on any Maven artifactory, neither Maven Central Repository nor Github Maven registry.

The landing website https://kpacha.github.io/ninja-mustache/ contains links for downloading the project itself. The repository https://github.com/kpacha/ninja-mustache contains the following directories:

  • ninja-mustache-demo
  • ninja-mustache-module

The ninja-mustache-demo imports the ninja-mustache-module in the pom.xml and serves as an example. It assumes the ninja-mustache-module was packed and installed to the local Maven repository manually through the command mvn clean install.

The only way I see is to include ninja-mustache-module as a Maven module into your repository and add it as a dependency.

Source https://stackoverflow.com/questions/70090016

QUESTION

Spring MVC Integration with Thymeleaf + Existing JSP apache tiles

Asked 2021-Dec-07 at 01:15

I am trying to configure Thymeleaf Html page with Spring MVC. I have controller method from which I am trying to return he thymeleaf template html page. Its existing project which uses spring mvc + tiles.I need to integrate thymeleaf in to existing project. The template Engine is autowired which is coming from different Jar file. I have provided configuration below. I am not getting any exception but getting Page Not found when I try to load the page.

IS it possible to have one flow which resolves view with Tiles + Jps and another flow with Thymeleaf template. how can I achieve it .

1   @Controller
2   @RequestMapping(&quot;/thymeleafConfiguration&quot;)
3   public class ConfigController {
4
5    @Autowired
6    TemplateEngine templateEngine; // This class is coming from different jar and I have 
7                                    //autowired. xml configuration is provided for reference
8    
9    
10    @PostConstruct   // Changes needs to apply only to certain class so I am using 
11                        //postconstruct method in controller 
12                        // where I need to use thymeleaf template. 
13    public void Init() {
14        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
15        templateResolver.setCacheable(false);
16        templateResolver.setPrefix(&quot;/templates/thymeleafPage/&quot;);
17        templateResolver.setSuffix(&quot;.html&quot;);
18
19        templateEngine.setTemplateResolver(templateResolver);
20
21        
22        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
23        resolver.setOrder(1);
24        resolver.setTemplateEngine(templateEngine);
25 
26    }
27    @RequestMapping(value = &quot;/view&quot;) // controller method where I am redirecting thymeleaf 
28                                         page
29    public String  viewTemplate(){      
30        return &quot;thymeleaf&quot;;
31    }
32}
33

application-context.xml

1   @Controller
2   @RequestMapping(&quot;/thymeleafConfiguration&quot;)
3   public class ConfigController {
4
5    @Autowired
6    TemplateEngine templateEngine; // This class is coming from different jar and I have 
7                                    //autowired. xml configuration is provided for reference
8    
9    
10    @PostConstruct   // Changes needs to apply only to certain class so I am using 
11                        //postconstruct method in controller 
12                        // where I need to use thymeleaf template. 
13    public void Init() {
14        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
15        templateResolver.setCacheable(false);
16        templateResolver.setPrefix(&quot;/templates/thymeleafPage/&quot;);
17        templateResolver.setSuffix(&quot;.html&quot;);
18
19        templateEngine.setTemplateResolver(templateResolver);
20
21        
22        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
23        resolver.setOrder(1);
24        resolver.setTemplateEngine(templateEngine);
25 
26    }
27    @RequestMapping(value = &quot;/view&quot;) // controller method where I am redirecting thymeleaf 
28                                         page
29    public String  viewTemplate(){      
30        return &quot;thymeleaf&quot;;
31    }
32}
33&lt;bean id=&quot;thymeleafProcessor&quot; class=&quot;com.java.ThymeleafTemplateProcessor&quot;&gt;
34    &lt;property name=&quot;templateEngine&quot; ref=&quot;templateEngine&quot;/&gt;
35&lt;/bean&gt;
36
37&lt;bean id=&quot;htmlStringTemplateResolver&quot; class=&quot;org.thymeleaf.templateresolver.StringTemplateResolver&quot;&gt;
38    &lt;property name=&quot;templateMode&quot; value=&quot;HTML&quot; /&gt;
39    &lt;property name=&quot;cacheable&quot; value=&quot;true&quot; /&gt;
40&lt;/bean&gt;
41
42&lt;bean id=&quot;templateEngine&quot; class=&quot;org.thymeleaf.spring4.SpringTemplateEngine&quot;&gt;
43    &lt;property name=&quot;enableSpringELCompiler&quot; value=&quot;true&quot; /&gt;
44    &lt;property name=&quot;templateResolvers&quot;&gt;
45        &lt;set&gt;
46            &lt;ref bean=&quot;htmlStringTemplateResolver&quot; /&gt;
47        &lt;/set&gt;
48    &lt;/property&gt;
49&lt;/bean&gt;
50

Project Structure :

1   @Controller
2   @RequestMapping(&quot;/thymeleafConfiguration&quot;)
3   public class ConfigController {
4
5    @Autowired
6    TemplateEngine templateEngine; // This class is coming from different jar and I have 
7                                    //autowired. xml configuration is provided for reference
8    
9    
10    @PostConstruct   // Changes needs to apply only to certain class so I am using 
11                        //postconstruct method in controller 
12                        // where I need to use thymeleaf template. 
13    public void Init() {
14        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
15        templateResolver.setCacheable(false);
16        templateResolver.setPrefix(&quot;/templates/thymeleafPage/&quot;);
17        templateResolver.setSuffix(&quot;.html&quot;);
18
19        templateEngine.setTemplateResolver(templateResolver);
20
21        
22        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
23        resolver.setOrder(1);
24        resolver.setTemplateEngine(templateEngine);
25 
26    }
27    @RequestMapping(value = &quot;/view&quot;) // controller method where I am redirecting thymeleaf 
28                                         page
29    public String  viewTemplate(){      
30        return &quot;thymeleaf&quot;;
31    }
32}
33&lt;bean id=&quot;thymeleafProcessor&quot; class=&quot;com.java.ThymeleafTemplateProcessor&quot;&gt;
34    &lt;property name=&quot;templateEngine&quot; ref=&quot;templateEngine&quot;/&gt;
35&lt;/bean&gt;
36
37&lt;bean id=&quot;htmlStringTemplateResolver&quot; class=&quot;org.thymeleaf.templateresolver.StringTemplateResolver&quot;&gt;
38    &lt;property name=&quot;templateMode&quot; value=&quot;HTML&quot; /&gt;
39    &lt;property name=&quot;cacheable&quot; value=&quot;true&quot; /&gt;
40&lt;/bean&gt;
41
42&lt;bean id=&quot;templateEngine&quot; class=&quot;org.thymeleaf.spring4.SpringTemplateEngine&quot;&gt;
43    &lt;property name=&quot;enableSpringELCompiler&quot; value=&quot;true&quot; /&gt;
44    &lt;property name=&quot;templateResolvers&quot;&gt;
45        &lt;set&gt;
46            &lt;ref bean=&quot;htmlStringTemplateResolver&quot; /&gt;
47        &lt;/set&gt;
48    &lt;/property&gt;
49&lt;/bean&gt;
50  myProject
51  |
52  |Src 
53        -Java
54        
55        -templates
56          -thymeleafPage        
57            - thymeleaf.html
58            
59        -webContent
60

web.xml

1   @Controller
2   @RequestMapping(&quot;/thymeleafConfiguration&quot;)
3   public class ConfigController {
4
5    @Autowired
6    TemplateEngine templateEngine; // This class is coming from different jar and I have 
7                                    //autowired. xml configuration is provided for reference
8    
9    
10    @PostConstruct   // Changes needs to apply only to certain class so I am using 
11                        //postconstruct method in controller 
12                        // where I need to use thymeleaf template. 
13    public void Init() {
14        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
15        templateResolver.setCacheable(false);
16        templateResolver.setPrefix(&quot;/templates/thymeleafPage/&quot;);
17        templateResolver.setSuffix(&quot;.html&quot;);
18
19        templateEngine.setTemplateResolver(templateResolver);
20
21        
22        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
23        resolver.setOrder(1);
24        resolver.setTemplateEngine(templateEngine);
25 
26    }
27    @RequestMapping(value = &quot;/view&quot;) // controller method where I am redirecting thymeleaf 
28                                         page
29    public String  viewTemplate(){      
30        return &quot;thymeleaf&quot;;
31    }
32}
33&lt;bean id=&quot;thymeleafProcessor&quot; class=&quot;com.java.ThymeleafTemplateProcessor&quot;&gt;
34    &lt;property name=&quot;templateEngine&quot; ref=&quot;templateEngine&quot;/&gt;
35&lt;/bean&gt;
36
37&lt;bean id=&quot;htmlStringTemplateResolver&quot; class=&quot;org.thymeleaf.templateresolver.StringTemplateResolver&quot;&gt;
38    &lt;property name=&quot;templateMode&quot; value=&quot;HTML&quot; /&gt;
39    &lt;property name=&quot;cacheable&quot; value=&quot;true&quot; /&gt;
40&lt;/bean&gt;
41
42&lt;bean id=&quot;templateEngine&quot; class=&quot;org.thymeleaf.spring4.SpringTemplateEngine&quot;&gt;
43    &lt;property name=&quot;enableSpringELCompiler&quot; value=&quot;true&quot; /&gt;
44    &lt;property name=&quot;templateResolvers&quot;&gt;
45        &lt;set&gt;
46            &lt;ref bean=&quot;htmlStringTemplateResolver&quot; /&gt;
47        &lt;/set&gt;
48    &lt;/property&gt;
49&lt;/bean&gt;
50  myProject
51  |
52  |Src 
53        -Java
54        
55        -templates
56          -thymeleafPage        
57            - thymeleaf.html
58            
59        -webContent
60&lt;servlet&gt;
61        &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt;
62        &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
63        &lt;init-param&gt;
64            &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
65            &lt;param-value&gt;classpath:spring-mvc.xml&lt;/param-value&gt;
66        &lt;/init-param&gt;
67        &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
68    &lt;/servlet&gt;
69
70    &lt;servlet-mapping&gt;
71        &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt;
72        &lt;url-pattern&gt;*.*&lt;/url-pattern&gt;
73    &lt;/servlet-mapping&gt;
74

Can you please guide me how can I load the Page. I have referred documentation of thymeleaf ThymeleafDocumetation Tutorial

I have followed some examples but couldnt find much difference. I appreciate your help. Jordan

ANSWER

Answered 2021-Dec-07 at 01:15

I have found the solution how to make it work for Jsp , HTML and Thymeleaf template together. Thank you

Source https://stackoverflow.com/questions/70130340

QUESTION

When I'm visiting another page, The images, logos, and icons are not displayed. In this project, I'm using the pug template engine and express.js

Asked 2021-Nov-30 at 11:00

When I'm visiting another page, images, logos, and icons are not displayed, but when I'm went back to the home page, images are displayed perfectly

In this project, I have used the pug template engine and express.js

Below link is the image of the project folder and files

Project folder and files image

Below link is the image of the home page

images, logos, and icons are displayed perfectly, but on the login and signup page I'm facing a problem with images

Home page

Below link is the image of the login and singup page

On this page, images are not displayed Problem!

login and singup page

Below section is express.js code

1const express = require(&quot;express&quot;);
2const app = express();
3const port = 80;
4const path = require('path');
5
6// &lt;------------------ define static mode  ------------------&gt;
7
8*// app.use(express.static('public'));*
9
10const staticpath = path.join(__dirname, '../public');
11app.use(express.static(staticpath));
12
13// &lt;------------------ Adding pug engine in express  ------------------&gt;
14app.set('view engine', 'pug');
15app.set('views', path.join(__dirname, '../view'));
16
17app.get('/', (req, res)=&gt;{
18    res.status(200).render('index.pug');
19})
20
21app.get('/loginandsingup.pug', (req, res)=&gt;{
22    res.status(200).render('loginandsingup.pug');
23})
24
25app.listen(port, ()=&gt;{
26     console.log(`application had started successfully on port ${port}`)
27})
28

below section is pug code of home page

1const express = require(&quot;express&quot;);
2const app = express();
3const port = 80;
4const path = require('path');
5
6// &lt;------------------ define static mode  ------------------&gt;
7
8*// app.use(express.static('public'));*
9
10const staticpath = path.join(__dirname, '../public');
11app.use(express.static(staticpath));
12
13// &lt;------------------ Adding pug engine in express  ------------------&gt;
14app.set('view engine', 'pug');
15app.set('views', path.join(__dirname, '../view'));
16
17app.get('/', (req, res)=&gt;{
18    res.status(200).render('index.pug');
19})
20
21app.get('/loginandsingup.pug', (req, res)=&gt;{
22    res.status(200).render('loginandsingup.pug');
23})
24
25app.listen(port, ()=&gt;{
26     console.log(`application had started successfully on port ${port}`)
27})
28.img#menu-icon
29  img(src=&quot;images/menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
30#navbarSupportedContent.collapse.navbar-collapse
31  .logo
32    a(href=&quot;/&quot;)
33      img(src=&quot;images/logo.png&quot;, alt=&quot;entre logo&quot;)
34  ul.navUl.navbar-nav.mb-2.mb-lg-0
35    li#nav-item-1.navList.nav-item
36      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
37    li#nav-item-1.navList.nav-item
38      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
39

Below section is pug code of login and singup page

1const express = require(&quot;express&quot;);
2const app = express();
3const port = 80;
4const path = require('path');
5
6// &lt;------------------ define static mode  ------------------&gt;
7
8*// app.use(express.static('public'));*
9
10const staticpath = path.join(__dirname, '../public');
11app.use(express.static(staticpath));
12
13// &lt;------------------ Adding pug engine in express  ------------------&gt;
14app.set('view engine', 'pug');
15app.set('views', path.join(__dirname, '../view'));
16
17app.get('/', (req, res)=&gt;{
18    res.status(200).render('index.pug');
19})
20
21app.get('/loginandsingup.pug', (req, res)=&gt;{
22    res.status(200).render('loginandsingup.pug');
23})
24
25app.listen(port, ()=&gt;{
26     console.log(`application had started successfully on port ${port}`)
27})
28.img#menu-icon
29  img(src=&quot;images/menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
30#navbarSupportedContent.collapse.navbar-collapse
31  .logo
32    a(href=&quot;/&quot;)
33      img(src=&quot;images/logo.png&quot;, alt=&quot;entre logo&quot;)
34  ul.navUl.navbar-nav.mb-2.mb-lg-0
35    li#nav-item-1.navList.nav-item
36      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
37    li#nav-item-1.navList.nav-item
38      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
39.img#menu-icon
40    img(src=&quot;./menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
41  #navbarSupportedContent.collapse.navbar-collapse
42    .logo
43      a(href=&quot;/&quot;)
44        img(src=&quot;./logo.png&quot; alt=&quot;entre logo&quot;)
45    ul.navUl.navbar-nav.mb-2.mb-lg-0
46      li#nav-item-1.navList.nav-item
47        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
48      li#nav-item-1.navList.nav-item
49        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
50

Any solution for this problem?

ANSWER

Answered 2021-Nov-30 at 05:57
1. Add this middleware in the app.js above you set view engine
1const express = require(&quot;express&quot;);
2const app = express();
3const port = 80;
4const path = require('path');
5
6// &lt;------------------ define static mode  ------------------&gt;
7
8*// app.use(express.static('public'));*
9
10const staticpath = path.join(__dirname, '../public');
11app.use(express.static(staticpath));
12
13// &lt;------------------ Adding pug engine in express  ------------------&gt;
14app.set('view engine', 'pug');
15app.set('views', path.join(__dirname, '../view'));
16
17app.get('/', (req, res)=&gt;{
18    res.status(200).render('index.pug');
19})
20
21app.get('/loginandsingup.pug', (req, res)=&gt;{
22    res.status(200).render('loginandsingup.pug');
23})
24
25app.listen(port, ()=&gt;{
26     console.log(`application had started successfully on port ${port}`)
27})
28.img#menu-icon
29  img(src=&quot;images/menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
30#navbarSupportedContent.collapse.navbar-collapse
31  .logo
32    a(href=&quot;/&quot;)
33      img(src=&quot;images/logo.png&quot;, alt=&quot;entre logo&quot;)
34  ul.navUl.navbar-nav.mb-2.mb-lg-0
35    li#nav-item-1.navList.nav-item
36      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
37    li#nav-item-1.navList.nav-item
38      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
39.img#menu-icon
40    img(src=&quot;./menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
41  #navbarSupportedContent.collapse.navbar-collapse
42    .logo
43      a(href=&quot;/&quot;)
44        img(src=&quot;./logo.png&quot; alt=&quot;entre logo&quot;)
45    ul.navUl.navbar-nav.mb-2.mb-lg-0
46      li#nav-item-1.navList.nav-item
47        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
48      li#nav-item-1.navList.nav-item
49        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
50  app.use(express.static(path.join(__dirname, &quot;public&quot;)));
51
2. Folder Structure
1const express = require(&quot;express&quot;);
2const app = express();
3const port = 80;
4const path = require('path');
5
6// &lt;------------------ define static mode  ------------------&gt;
7
8*// app.use(express.static('public'));*
9
10const staticpath = path.join(__dirname, '../public');
11app.use(express.static(staticpath));
12
13// &lt;------------------ Adding pug engine in express  ------------------&gt;
14app.set('view engine', 'pug');
15app.set('views', path.join(__dirname, '../view'));
16
17app.get('/', (req, res)=&gt;{
18    res.status(200).render('index.pug');
19})
20
21app.get('/loginandsingup.pug', (req, res)=&gt;{
22    res.status(200).render('loginandsingup.pug');
23})
24
25app.listen(port, ()=&gt;{
26     console.log(`application had started successfully on port ${port}`)
27})
28.img#menu-icon
29  img(src=&quot;images/menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
30#navbarSupportedContent.collapse.navbar-collapse
31  .logo
32    a(href=&quot;/&quot;)
33      img(src=&quot;images/logo.png&quot;, alt=&quot;entre logo&quot;)
34  ul.navUl.navbar-nav.mb-2.mb-lg-0
35    li#nav-item-1.navList.nav-item
36      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
37    li#nav-item-1.navList.nav-item
38      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
39.img#menu-icon
40    img(src=&quot;./menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
41  #navbarSupportedContent.collapse.navbar-collapse
42    .logo
43      a(href=&quot;/&quot;)
44        img(src=&quot;./logo.png&quot; alt=&quot;entre logo&quot;)
45    ul.navUl.navbar-nav.mb-2.mb-lg-0
46      li#nav-item-1.navList.nav-item
47        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
48      li#nav-item-1.navList.nav-item
49        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
50  app.use(express.static(path.join(__dirname, &quot;public&quot;)));
51|__public/   
52    |__ css/
53        |__ css files...
54    |__ js/
55        |__ js files...
56
3. Import this way

Now you set the path to the public directory you have to give the path public folder when you import

1const express = require(&quot;express&quot;);
2const app = express();
3const port = 80;
4const path = require('path');
5
6// &lt;------------------ define static mode  ------------------&gt;
7
8*// app.use(express.static('public'));*
9
10const staticpath = path.join(__dirname, '../public');
11app.use(express.static(staticpath));
12
13// &lt;------------------ Adding pug engine in express  ------------------&gt;
14app.set('view engine', 'pug');
15app.set('views', path.join(__dirname, '../view'));
16
17app.get('/', (req, res)=&gt;{
18    res.status(200).render('index.pug');
19})
20
21app.get('/loginandsingup.pug', (req, res)=&gt;{
22    res.status(200).render('loginandsingup.pug');
23})
24
25app.listen(port, ()=&gt;{
26     console.log(`application had started successfully on port ${port}`)
27})
28.img#menu-icon
29  img(src=&quot;images/menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
30#navbarSupportedContent.collapse.navbar-collapse
31  .logo
32    a(href=&quot;/&quot;)
33      img(src=&quot;images/logo.png&quot;, alt=&quot;entre logo&quot;)
34  ul.navUl.navbar-nav.mb-2.mb-lg-0
35    li#nav-item-1.navList.nav-item
36      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
37    li#nav-item-1.navList.nav-item
38      a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
39.img#menu-icon
40    img(src=&quot;./menu-icon.svg&quot;, alt=&quot;Menu icon&quot;)
41  #navbarSupportedContent.collapse.navbar-collapse
42    .logo
43      a(href=&quot;/&quot;)
44        img(src=&quot;./logo.png&quot; alt=&quot;entre logo&quot;)
45    ul.navUl.navbar-nav.mb-2.mb-lg-0
46      li#nav-item-1.navList.nav-item
47        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Home
48      li#nav-item-1.navList.nav-item
49        a.navLink.nav-link.text-dark(href=&quot;#&quot;) Order
50  app.use(express.static(path.join(__dirname, &quot;public&quot;)));
51|__public/   
52    |__ css/
53        |__ css files...
54    |__ js/
55        |__ js files...
56&lt;link rel=&quot;stylesheet&quot; href=&quot;/css/main.css&quot; /&gt;
57
NOTE:-

One more thing public directory in root and also app.js file should be in the root if you want app.js in src then set path accordingly

You should now be all set up to access CSS or any file

Source https://stackoverflow.com/questions/70164886

QUESTION

Error while outputting template engine maximum recursion depth exceeded while calling a Python object

Asked 2021-Nov-11 at 16:10

The problem is that I get an error when I try to display a block on a page, I don't really know what to do, since I'm working with a template engine for the first time. this is code of views.py

1class IndexView(generic.ListView):
2template_name = 'Homepage/index.html'
3model = Goods
4context_object_name = 'goods'
5
6def sale(request):
7    return render(request, 'articles/sale.html')
8

this is code of index.html

1class IndexView(generic.ListView):
2template_name = 'Homepage/index.html'
3model = Goods
4context_object_name = 'goods'
5
6def sale(request):
7    return render(request, 'articles/sale.html')
8{% include "article/sale.html" %}
9{% block sale %}
10
11{% endblock %}

this is code of sale.html

1class IndexView(generic.ListView):
2template_name = 'Homepage/index.html'
3model = Goods
4context_object_name = 'goods'
5
6def sale(request):
7    return render(request, 'articles/sale.html')
8{% include "article/sale.html" %}
9{% block sale %}
10
11{% endblock %}{% extends "Homepage/index.html" %}
12
13{% block sale %}
14
15&lt;td class ="sale"&gt;
16      &lt;img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png"&gt;
17
18        &lt;h1 class="description"&gt;ОписаниеОписаниеОписаниеОписание&lt;/h1&gt;
19
20  &lt;a class="buy" href="#openModal" &gt;
21    &lt;span &gt;Купить&lt;/span&gt;&lt;/a&gt;
22  &lt;h1 class="price"&gt;цена&lt;/h1&gt;
23  &lt;/td&gt;
24
25
26{% endblock %}

This is building a template введите сюда описание изображения

in the end it gives an error maximum recursion depth exceeded while calling a Python object вот TraceBack введите сюда описание изображения

ANSWER

Answered 2021-Nov-11 at 16:10

Your index.html template includes the sales.html template, and the sales.html template extends the index.html template. As a result if you render index.html or sale.html, it will get stuck in an infinite loop.

You can remove the {% include 'article/sales.html' %} part of the index.html page. The fact that you defined a block that can be filled in by the sales.html template is sufficient.

Source https://stackoverflow.com/questions/69931323

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Template Engine

Tutorials and Learning Resources are not available at this moment for Template Engine

Share this Page

share link

Get latest updates on Template Engine