Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo javascript with a php function inside?

Tags:

php

Oh boy! I cant get this to work. Any ideas on what the heck I'm doing wrong? Here's the code.

I'm trying to echo the script but use a php function to get the directory of the js file!!

Any help would be appreicated!!

echo '<script src="<?php get_some_function();?> . /js/main.js"></script>';

I've tried dif scenerios with escaping but cant get this to output correctly.

like image 421
lnickel Avatar asked Jan 16 '26 21:01

lnickel


2 Answers

Since you're already in the PHP context, you can simply concatenate the strings, like so:

echo '<script src="' . get_some_function() . '/js/main.js"></script>';

Using sprintf() looks more cleaner, though:

echo sprintf('<script src="%s/js/main.js"></script>', get_some_function());
like image 60
Amal Murali Avatar answered Jan 19 '26 11:01

Amal Murali


Instead of opening another script tag inside the string, concat the string and echo. The <?php within your string will not be evaluated.

echo '<script src="'. get_some_function() . '/js/main.js"></script>';
like image 34
Matt S Avatar answered Jan 19 '26 09:01

Matt S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!