Ali Abbas
Ali Abbas

Reputation: 45

Adding image using javascript in jade

I have the following layout.jade code and I want to make some changes to the javascript so that every time the page is reloaded I can load some image to the page. I want to do this using jade. Here is the code that I currently have:

html
  head
    title= title
    script(src='/libs/jquery/jquery.min.js')
    link(rel='stylesheet', href='/libs/bootstrap/css/bootstrap.min.css')
    link(rel='stylesheet', href='/stylesheets/style.css')

  body
      script(type='text/javascript').
       if (document.cookie.indexOf('mycookie')==-1) {
        document.cookie = 'mycookie=1';
       }
       else {
        alert('You refreshed!');
       }
    block content

It works fine for the refresh and gives me alert. I have 10 images and I want to add them to the page in a loop such that everytime the page is refreshed the next image is loaded and then after the last image it goes to the first one. I can try using for loop instead of the alert message to load images but when I try to add image using standard way of jade in the else statement no image is shown.

I have tried creating a reload.js page and then calling it in the app and so on.

Can anyone help me in how can I get a image from image folder like

  img(border="0" src="images/3.jpg")

by making changes to this. I want to see if page is reloaded and then a different image is loaded.

Thanks

Upvotes: 0

Views: 823

Answers (1)

laggingreflex
laggingreflex

Reputation: 34627

There could be a number of ways to do this. Here's one: You could use sessions on server-side (which IMO is better to work with than cookies in client-side JS) to create a variable that holds the image you want (based on the variable) and pass it to jade which simply compiles the HTML with that image.

Something like this:

server

app.get('/', function(req, res){
    // incrementation logic
    if(!req.session.myimage)
        req.session.myimage = 0;
    req.session.myimage++;
    if(req.session.myimage > 10)
        req.session.myimage = 1;

    // pass it onto Jade
    res.locals.myimage = req.session.myimage;

    res.render('index');
});

jade

img(border="0" src="images/#{myimage}.jpg")

Upvotes: 1

Related Questions