How to get home url in a javascript file

Hi,

I would like to use a variable set with twig but into a javascript file.
for now this is how I do it :

<script>
    var baseUrl = "{{ url('theme://') }}";
    var homeUrl = "{{ home_url }}";
</script>
<script src="{{ url('theme://js/main.js') }}" ></script>

But I’m pretty sure, there’s a better / safer / cleaner way to do it. On wordpress, I was able to put my var directly in my javascript file with the function.php file. Is there something like this around here ?

Thank you very much

@Michael Because your mention ‘function.php’, I presume your would like to add an inline script from within php of your theme or plugin.

You could use the Asset Manager’s method Assets::AddInlineJS for that:

$this->grav['assets']->addInlineJs('alert(\'This is inline!\')');

The above statement results in:

<script>
   alert('This is inline!')
</script>

Hope this helps…

Hi @pamtbaau,
thanks for your answer.

No this is not what I want to do. I want to write my baseUrl and my homeUrl vars directly inside my javascript file.

So my footer only looks like this :

<script src="{{ url('theme://js/main.js') }}" ></script>

Thank you

@Micheal Are you referring to the function wp_localize_script( $handle, $name, $data ) from Wordpress?

Please correct me when my info is outdated, but to my knowledge the variable is not injected magically into the javascript file.

wp_localize_script() inserts a <script> tag into the html page. The <script> contains a variable named after $name and has the value of $data assigned to it.

Just wondering, how would it insert a variable into a minified and uglified javascript file where all variables have been renamed?