Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

General

How to get home url in a javascript file

Solved by pamtbaau View solution

Started by Michael Garcia 8 years ago · 3 replies · 2550 views
8 years ago

Hi,

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

TWIG
<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

8 years ago

@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:

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

The above statement results in:

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

Hope this helps...

8 years ago

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 :

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

Thank you

8 years ago Solution

@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?

last edited 08/30/18 by pamtbaau

Suggested topics

Topic Participants Replies Views Activity
General · by Jerry Hunt, 4 days ago
2 99 16 hours ago
General · by pamtbaau, 21 hours ago
1 63 21 hours ago
General · by Andy Miller, 1 day ago
0 48 1 day ago
General · by Marcel, 12 months ago
6 357 5 days ago
General · by Duc , 6 days ago
3 45 6 days ago