Last active
July 17, 2018 21:09
-
-
Save Draphar/88600339d066cd6fb9e20f39fdcae72f to your computer and use it in GitHub Desktop.
Easy method to pass server side variables to inline or extern JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var text = document.currentScript.getAttribute('data-variable'); // text is now 'Lorem ipsum dolor sit amet' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Using PHP for this example. You can use any server side language which can output something to the site. | |
* Made by Draphar | |
*/ | |
$variable='Lorem ipsum dolor sit amet'; // any value which can be transformed into a string | |
?> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<script> | |
var text = "<?php echo htmlentities($variable);?>"; // easy for inline scripts | |
</script> | |
<script src="extern.js" data-variable="<?php echo htmlentities($variable);?>"></script> | |
</head> | |
<body> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment