1

I want to change a hyperlink inside a script with a variable. It's the FB SDK, i want to display the SDK in the language the user chose on my website.

The variable is {$lang_fb} and returns the correct result (here:en_US) if I use it in normal php.

If I use the variable inside a script on a plain HTML page there is no result.

The script:

<script>
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/{$lang_fb}/sdk.js#xfbml=1&version=v2.5&appId=01234567890";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<script>

results in the identical code in the page

What can I do?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Stan
  • 129
  • 12

4 Answers4

1

If you are in a PHP script, you need to put the php tags or escape the string.

Way one

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/<?php echo {$lang_fb} ?>/sdk.js#xfbml=1&version=v2.5&appId=01234567890";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

Way two

<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/".{$lang_fb}."/sdk.js#xfbml=1&version=v2.5&appId=01234567890";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

If you don't share more code we can't view what happens.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
1

The soluition:

 js.src = "//connect.facebook.net/{/literal}{$lang_fb}{literal}/sdk.js#xfbml=1&version=v2.5&appId=1234567890";

Thanks for your help!!!

Stan
  • 129
  • 12
0

Since you are using a file extension, that is not PHP related, you need to setup php to process this extension.

For apache you can do this with the file .htaccess:

AddHandler application/x-httpd-php .tpl

Of course you also need to require the Facebook SDK which creates {$lang_fb}.

Community
  • 1
  • 1
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
-2

$lang_fb is a php variable and will not work in javascript. Are you embedding your script tag within php file? If yes then you can simply use the following:

<script>
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/"+<?php echo $lang_fb; ?>+"/sdk.js#xfbml=1&version=v2.5&appId=01234567890";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>
ataravati
  • 8,891
  • 9
  • 57
  • 89
yasirfarooqui
  • 193
  • 1
  • 9