4

Seems like it should be pretty straightforward, but I'm having a really hard time finding an answer.

How do you find the current page's URL within a Nunjucks template?

Something like this would be perfect:

<a href="{{ page.url }}">Some link</a>
saricden
  • 2,084
  • 4
  • 29
  • 40
  • What about adding `window` to the `nunjucks` context and then using `window.location.href`? – xmojmr Oct 30 '18 at 11:08
  • 2
    That's a good idea, but after attempting to implement, it's looking like this won't work out of box because certain gulp environments don't have access to the `window` object, ie if you were running test. Anyways when I tried it shouted at me that `window` was undefined. – saricden Oct 31 '18 at 01:20
  • Oh woops I should have mentioned I'm using gulp. I'll update the question. – saricden Oct 31 '18 at 01:21
  • 1
    Does anyone have the solution to this question? – ukalpa Apr 29 '19 at 21:32

3 Answers3

0

depends on attributes of your request obejct, if it's wsgi request from django, I simply print it as {{ request.build_absolute_uri }}

ziqi deng
  • 46
  • 2
0

I find the following benefical if you have a single page URL that loads. If you are building your gulp nunjucks projects with the help of browser-sync, you can build a relationship between the two, by accessing browser-sync's options through a callback. Then pass that data back into a nunjucks environmental variable.

Here are the steps

  1. create an empty global variable
  2. user browserync's callback function to get a browsersync option for urls
  3. pass that value into the empty global variable in step 1
  4. now tell nunjucks to create an environmental variable that references the global variable from step 1.
  5. build the project.
  6. reference the nunjucks environmental variable in your template.

Below is an "idea" from your gulpfile.js file, but will require tweaking depending on your setup...


const browserSync = require('browser-sync');

//step 1
let mURL  = '';

//...

//step 4...
const manageEnvironment = function (environment) {
  environment.addGlobal('mURL', mURL);
}

function genNunJucks(cb) {
//...
   .pipe(nunjucksRender({
       manageEnv: manageEnvironment,
    });
//...
}

//...

const msync = browserSync.create();
function bSync(cb) {
msync.init({
        port: 49673,
        ui: {
            port: 3002,
        },
        listen: "gulp.wlc",
        browser: "default",
},
//step 2...
callbacks: {
    ready: function (err, bs) {
      //step 3...
      mURL = bs.options.getIn(['urls', 'local']);
    }
  }
});

//watch stuff...

}

//step 5
//npm start

//step 6...
/**
from witin your template, once the project is running, 
you should have acces to {{mURL}}, 
and yes you can do <a href="{{ mURL }}">Some link</a> 
all due to the help of browser-sync.
**/

klewis
  • 7,459
  • 15
  • 58
  • 102
-1

Try something like this: {{ request.headers.referer }},

or this: {{ request.url }}.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83