Import image from javascript to .pug - javascript

I'm new to web development and trying to learning how to use javascript and .pug. I have set var camgrounds with image files
router.get('/campgrounds', function (req, res) {
var campgrounds = [
{
title: "Paynetwon Campground",
image: img(src ="https://cdn.pixabay.com/photo/2020/06/14/17/57/mountains-5298769_960_720.jpg")
}];
res.render('campground', {
campgrounds: campgrounds
});
});
When I try to go campgrounds render page, i have error message "img is not defined"
On my camground.pug, i wrote as:
doctype html
each camping in campgrounds
ul
li= camping.title
li = camping.image
can someone help with this error code?

Bankole is right, you should just pass the image path to Pug and let Pug do the rest. However, the correct markup for creating an image in Pug would look like this. (And if you want a list of campgrounds, I'd suggest moving the ul element outside the loop as follows:)
ul
each camp in campgrounds
li
p= camp.title
img(src= camp.image)

Found it.. it was just
img(src=camp.image)

Related

Passing mongoose documents to view and use in script tag node.js

I have an app running in Node.js with Express, and I wanted to dinamically change options on select object with jquery. This is actually not a big problem, but I'm having troubles on using the res.render parameters (which are mongoose documents) in the script tag. I use them without any trouble on the html (jade actually), but in the script tag I get a problem with the ObjectId not being a String.
This is an extract of the code:
On the backend:
router.get("/new", function(req, res){
res.render("session/documentos/new",
{
services: res.locals.services
});
});
On the view
block content
div
h1(class="text-center") New document
form(id="newDoc" action="/session/documentos" method="POST")
div(class="tab") Service:
div(class="form-group")
select(class="form-control" name="svc" id="svc")
option(value="undefined" disabled selected) Choose one
for service in services
option(value=service._id)=service.name
script.
$(document).ready(function() {
var sessLenght = 0;
var selectedSvc = #{services};
$("#svc").change(function(){
console.log("Service changed: " + selectedSvc);
});
});
And this is the error I'm getting:
Console error
And in Sources:
Source error on ObjectId
So I'm being able to use with no troubles the "services" collection of documents, but when trying to use them on the script tag I'm getting problems with the ObjectId element.
I was thinking that one soution would be to convert to string the ObjectId when querying the database, but I think there might be a cleaner solution to that. Which might be the best way to solve the issue?
Any thoughts appreciated! Thanks in advance
Try to change var selectedSvc = #{services};
to var selectedSvc = !{services};
or var selectedSvc = !{JSON.stringify(services)};

Rendering image onto server-side using base64 not working correctly

First off - this is my first post on here, and so I preface this question with a big thanks for the many months of anonymous help I've received in the process of building my first real site. That's also to say, please forgive me if the formatting of this question (and my code LOL) isn't up to par. I'll try to include only what's relevant. That said, I'm having some issues with rendering a base64 string onto a pug template.
I'm sending off an image file to an API (in this case, a JPG) via form input with enctype='multipart/form-data'. I've gotten that to work quite nicely. However, I'd also like to grab the image that is uploaded and display it on the route that I render to after the API responds.
articles.js:
...
router.post('/add', upload.single(), function(req, res) {
if(req.files.upfile.data) {
global.d = new Buffer(req.files.upfile.data, 'binary').toString('base64') // I receive the data initially as a <Buffer> object //
// api formatting after here//
let article = new Article();
//assign article attributes 1-5, author,etc
article.image = d;
article.save((err) => {
if(err) {
console.log(err);
} else {
req.flash('success', 'Log Added')
res.redirect('/');}
});
}
});
...
router.get('/:id', function(req, res){
Article.findById(req.params.id, function(err, article){
User.findById(article.author, function(err, user){
res.render('article', {
article: article,
author: user.name,
first: article.first,
second: article.second,
third: article.third,
fourth: article.fourth,
fifth: article.fifth,
total: article.total,
image: article.image
});
});
});
});
which renders onto:
article.pug
extends layout
block content
h1 #{author}'s day
h4 from #{article.title}
br
br
ul
li.list-group-item.d-flex.justify-content-between.align-items-center.list-group-item-success Sadness.
span.badge.badge-primary.badge-pill #{first}
br
li.list-group-item.d-flex.justify-content-between.align-items-center.list-group-item-success Anger.
span.badge.badge-primary.badge-pill #{second}
br
li.list-group-item.d-flex.justify-content-between.align-items-center.list-group-item-success Disgust.
span.badge.badge-primary.badge-pill #{third}
br
li.list-group-item.d-flex.justify-content-between.align-items-center.list-group-item-success Neutral.
span.badge.badge-primary.badge-pill #{fourth}
br
li.list-group-item.d-flex.justify-content-between.align-items-center.list-group-item-success Happiness.
span.badge.badge-primary.badge-pill #{fifth}
br
li.list-group-item.d-flex.justify-content-between.align-items-center.list-group-item-success Happiness.
span.badge.badge-primary.badge-pill #{image}
img(src='data:image/jpeg;base64,#{image}')
I get the missing image icon, even though my base64 works on every online decoder I've used, and even if I hardcode the base64 string into the link as <img src = "data:image/jpeg;base64,DATA_HERE"> on a test html file. And if I insert p #{image} onto the line before I attempt to use #{image}, I get something like this (which seems to be valid to me, but I think I just need a more experienced eye to look at this):
/9j/4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNtcwIQAABtbnRyUkdCIFhZWiAH3AABABkAAwApADlhY3NwQVBQTAAAAAAAAAAAAAA ... DTvL/734mAqYiBciDqO8FmafV/UiJb3V9kn//Z
Ahh please tell me what I'm misunderstanding! I've searched through every post on SO and haven't been able to fix my error. Any input is very much appreciated. Thank you again!
EDIT: writing image/jpg and image/jpeg gives me the same empty image icon
I had a similar problem and I think it's because the binary data is not in the right format for Pug. Try this in your route, it worked for me:
router.get('/:id', function(req, res){
Article.findById(req.params.id, function(err, article){
User.findById(article.author, function(err, user){
res.render('article', {
article: article,
author: user.name,
first: article.first,
second: article.second,
third: article.third,
fourth: article.fourth,
fifth: article.fifth,
total: article.total,
image: article.image.toString('base64')
});
});
});
});
So change your image line to:
image: article.image.toString('base64')

Display data from database (using mongodb) in hbs/html file Node.Js

I started studying node.js, and now I'm trying to do a "Todo-App".
I'm trying to find the best way to transfer data from my database (using mongodb) into my hbs files, so I could display it.
From the server.js -> server to the hbs -> client (correct to me if I'm wrong please, by assuming that server.js is the server of course and the hbs file is the client)
So, I succeeded to do it by passing an array.
but when I'm trying to display in html desing, it just looking bad.
The code:
app.get('/allTasks',(req,res)=>{ //get (go to) the allTasks (hbs file)
Todo.find().then((todos) => {
console.log(todos);
var arrayOfTodos = [];
todos.forEach(function(element){
console.log("\n\n\n\n\n elemnt details: ",element.text + "\n",element.completed+"\n");
arrayOfTodos.push(element.text,element.completed);
});
res.render("allTasks.hbs", {
pageTitle: "Your tasks: ",
todos: arrayOfTodos
});
});
});
The result is:
You can see a picture
As you can see, its just looking bad... cause it just display an array,
an I want to display each task seperately.
Any tips?
Thanks a lot,
Sagiv
Instead of using push just do:
Todo.find().toArray(function(err, result){
arrayOfTodos = result;
})
Once you have your array, the design got nothing to do with mongodb. You will need to learn how to use your render technology. You need to touch your html template, so you should start by posting that.
The problem solved.
I just had to learn how to handle the data in the hbs side.
so the code is: (in hbs)
{{#each todos}}
{{missionNumber}} <br>
{{text}}<br>
completed = {{completed}}<br><br>
{{/each}}
as you can see, the each is a loop , that pass on the todos parameter (my array)
and i just have to display the data in the way i want it to be displayed.
thanks for your help.

Render ExpressJS into div identified by id

I am new to the ExpressJS and Jade game, as like today new. I can't figure out how to render data into a div identified by its id attribute. Here is my sample Jade file:
extends layout
block content
div
h1= title
div(id="content", class="main")
I want to pass the data into the div with id Content. Here is the snippet of my ExpressJS file:
...
router.get('/', function(req, res, next) {
res.render('index', { title: 'Hello World!' });
res.render('index', { content: 'Wazzzaaapp' });
});
...
I'm able to display the title Hello world but not the Wazzzaaapp.
Sample screenshot of what I got:
Is this possible to do in render or am I missing something?
I'm not sure if this is the correct or actual answer, but I got it solved by adding (in the Jade/ Pug file of course) either the placeholder #{var_name} or = var_name as:
div(id="content", class="main")= content
OR
div(id="content", class="main") #{content}
either one works and shows the Wazzzaaapp output as intended:
Hope this solution helps others!

passing array of image objects to the jade and then displaying via jade

Here, I have use.js and use.jade.
In use.js, I am simply mapping hardcoded image variable img_01 from jade to use.js by specifying var $image= $(pclass + 'img_01');
In .js, I am assigning $image by some useful image using
$image.attr('src', useful_image)
Using img.use--img_01 in .jade, I am able to display the image (useful_image).
Now, my constraint is I don't want to hard code in .jade and let .jade display images as many as provided by .js.
So, I am able to create the array in .js of var $image=[] and then $image.push($(pclass + 'img_' + N.toString()) where N varies from 0 to K (lets say K =3).
Now I want to call these img_0, img_1, img_2 .....img_K in .jade and display them on page.
So my specific question is I am not able to iterate [img_0, img_1, img_2 .....img_K] in .jade. Can anyone tell what could be best method to do so????
Pls note: I used rendering method. For the same I used
var express = require('express');
var app = express();
But, node.js gets crashed with this itself leave aside using app.get...
You can pass object from server to client in this way.
app.get(..., function (req, res) {
var stats = { ... };
res.render('chart', { images: $arrImage });
});
For looping at client ,you can use jade#each.
each oneImage in images
img( src=oneImage.image)
Note : Jade is depricated,So try to use Pug#each

Categories

Resources