Best Way Of Getting Base URL Inside KnockoutJS .html File

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="" />


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>