lnickel
lnickel

Reputation: 351

Echo javascript with a php function inside?

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.

Upvotes: 2

Views: 1105

Answers (5)

Altaf Hussain
Altaf Hussain

Reputation: 5202

Remember that any variable echoed in single quotes ( ' ' ), the value of that variable will be not printed, and if a variable is echoed in double quotes ( " " ) it will be printed.

Similar is true for returned data from a function stored in a varaible. If you are using single quotes, then every php code (variable, or a method call of a class) should be concatenated using dot operator ( . , :P ) . If you are using double quotes, then no need to use . .

Like in all above answers, they have used . to append the php function call, your code may be fine as below also (not tested by me, so you will need to do adjustment) :

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

But please note that it is a best practice to use single quotes for any kind of html etc echoed in php code, because HTML attributes are using double quotes.

Hope this will help...

Upvotes: 1

Amal
Amal

Reputation: 76646

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());

Upvotes: 5

joe42
joe42

Reputation: 657

try doing this:

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

or this:

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

Upvotes: 3

knittl
knittl

Reputation: 265908

Simple string concatenation:

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

Don't forget to properly escape the output of your function!

Upvotes: 3

Matt S
Matt S

Reputation: 15394

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>';

Upvotes: 4

Related Questions