Currin Berdine
Currin Berdine

Reputation: 285

How do I add a query parameter to a URL?

What's the best practice for adding a query parameter to a URL in Tritium (Moovweb SDK)? Looking for something that works where you don't know if the URL has a "?" and other query parameters already.

Upvotes: 2

Views: 279

Answers (2)

nmakiya
nmakiya

Reputation: 316

I think there is going to be a new URL scope soon so you'll be able to do things like this much more easily!

Upvotes: 1

michael
michael

Reputation: 209

Here's a short snippet of Tritium that should help you out in your Moovweb project. Just replace the "query_param=true" bit with the query parameter you want to add.

It selects the href of every a tag, then looks for any existing query parameters (by looking for a "?" in the href). If there are some existing, it just appends the new query parameter. If there are no existing query parameters on the href, it uses the ? to add one to the URL.

$q = "query_param=true"
$("//a[@href]") {
  %s = fetch("./@href")
  match(%s) {
    with(/\?/) {
      attribute("href", %s + "&" + $q)
    }
    else() {
      attribute("href", %s + "?" + $q)
    } 
  }
log(%s) 
}

(You could also turn that into a function if you wanted!)

Upvotes: 3

Related Questions