Get current URL in Nunjucks template?

3.7k views Asked by At

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>
3

There are 3 answers

0
Martin Žák On

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

or this: {{ request.url }}.

0
ziqi deng On

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

0
klewis On

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.
**/