0

I have created a custom JavaScript file in a Magento 2.1.7 theme that serves a different logo depending on the month.

The .js file is in app/design/ inside the theme’s /web/js/ folder. The logos are in the theme’s /web/images/ folder.

The .js contains switch/case code with relative links to the images ../images/logo1.png etc.

I assumed that once deployed and the files had moved to pub/static that it would work, but it didn’t. The images aren’t being transferred from the theme web/images folder to the pub/static images folder.

I have got it working by using links from the root to /pub/media/logos/logo1.png but are there better ways of achieving this? I would appreciate help. I’m assuming that there aren’t any directives with a shortcut to the pub/media folder that can be used in JavaScript?

Manoj Deswal
5,80325 gold badges29 silver badges50 bronze badges
asked Sep 8, 2017 at 0:52
1
  • Use url.build() function in js to get url path. Commented Sep 8, 2017 at 5:07

1 Answer 1

0

You can set the URL in your PHTML file and pass it through to your JS like so:

PHTML

<script type="text/x-magento-init">
 {
 "*": {
 "yourJsAliasHere": {
 "imageUrl": "<?php echo $block->getViewFileUrl('images/image-name.jpg'); ?>"
 }
 }
 }
</script>

JS

define([
 'jquery'
], function ($) {
 'use strict';
 return function(config) {
 alert(config.imageUrl);
 }
});
answered Sep 8, 2017 at 8:49
2
  • Is it possible without changes to the theme's phtml? I always try to avoid making changes to keep my upgrades easier and usually only create a module for more larger functions. The part of the js with the path I’m currently using is... case 8: case 9: case 10: logoimg = "/pub/media/logos/logo-autumn.png"; Commented Sep 8, 2017 at 9:17
  • You could do it this way but it isn't much better than hardcoding it, personally I find following best practices to be better than using 'dirtier' methods just for the sake of not overriding a template. Commented Sep 8, 2017 at 13:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.