pug how to set dynamic src

32 views Asked by At
script.
  let thisfilefullname = document.URL.substring(document.URL.lastIndexOf('/') + 1, document.URL.lastIndexOf('.'));
  let imgurl = './img';
  if(thisfilefullname.indexOf('localhost') == -1  && thisfilefullname != 'index') { imgurl = '../img'; } //'localhost' will be changed
h1.head_logo
  a(href="/", title="홈으로 이동")
    img(src= imgurl+"/logo.png", alt="description") //imgurl : undfined

Is there no way to inline some variables to pug? Should I use 'document.getElementById(...)'?

1

There are 1 answers

2
Sean On

Pug compiles server-side before any code is sent to the browser. Pug attribute interpolation (in other words, things like src= imgurl) is evaluated as part of that compiling process.

In contrast, the JavaScript you've written inside that script tag runs client-side, in the browser, after Pug has fully compiled. Pug doesn't have access to variables defined in client-side JavaScript, and doesn't have access to document, because it doesn't exist yet.

In short, your current code tries to use variables on the server that don't get defined until after compilation has happened and Pug is no longer part of the picture.