1

How can I get the base URL inside a KnockoutJS HTML file? See file below:

app/design/frontend/<Vendor>/<Theme>/Magento_Checkout/web/template/<Filename>.html
  • did you solve this? – simonthesorcerer Oct 4 '17 at 10:38
  • No am still looking for the answer. Any help would be greatly appreciated :-) – Ryan Copeland Oct 4 '17 at 14:55
4

There are three parts to this, I will use the checkout authentication as an example but this should work in any KO/JS file that has mage/url as a dependency.

vendor/magento/module-checkout/view/frontend/web/js/view/authentication.js
vendor/magento/module-checkout/view/frontend/web/template/authentication.html

Setting up the URL in the JS file

Add mage/url to the list of dependencies.

Add the following function to the JS file:

getBaseUrl: function() {
    return url.build('testing');
},

Use Knockout to set the href

<a data-bind="attr: { href: getBaseUrl() }">Link here 2</a>

Result

I had to clear Varnish and browser cache.

<a href="http://localhost:3000/testing" data-bind="attr: { href: getBaseUrl() }">Link here 2</a>
11

I managed to do this in app/design/frontend/<Vendor>/<Theme>/Magento_OfflinePayments/web/template/<Filename>.html, but the solution should work in the Magento_Checkout as well.

When you inspect the window variable in the dev-console of your browser, you will see that the checkout and checkoutConfig objects are available on checkout-pages.

Here are the relevant parts:

checkout.baseUrl
checkout.checkoutUrl
checkout.customerLoginUrl
checkout.removeItemUrl
checkout.shoppingCartUrl
checkout.updateItemQtyUrl

checkoutConfig.cartUrl
checkoutConfig.checkoutUrl
checkoutConfig.defaultSuccessPageUrl
checkoutConfig.forgotPasswordUrl
checkoutConfig.pageNotFoundUrl
checkoutConfig.registerUrl
checkoutConfig.staticBaseUrl

In my case, I wanted to display an image; here's the code:

<img data-bind="attr: {'src':checkoutConfig.staticBaseUrl + 'frontend/<Vendor>/<Theme>/<Locale>/images/logo.png'}" alt="" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.