Laravel's past variable recognition problem for JavaScript

0

I'm developing a web application with Laravel and I noticed something strange.

When passing a variable from Laravel to the HTML page two different behaviors are happening:

  • When calling the variable in an internal script in HTML it is recognized;

  • However, when calling the variable in an external script, in a JavaScript file referencing it at the end of the HTML body tag, it is not recognized.

Does anyone know why this kind of behavior happens?

Below is a sample of the code used in Laravel:

<!DOCTYPE html>
<html lang=pt-br>

<head>
	<meta charset="utf=8">
	<title>Teste</title>

</head>

<body>

<div>
<img class="destaque1" src="{{ asset('images/banners/00004.jpg') }}">
</div>

<script>
var stringImagensBanners = "{{ $imagensBanners }}";
var banners = stringImagensBanners.split(",");
var bannerAtual = 0;

function trocaBanner() {
	document.querySelector('.destaque1').src = banners[bannerAtual];
	bannerAtual = (bannerAtual + 1);

	if (bannerAtual == 5) {
	bannerAtual = 0;
	} return false;
}

setInterval(trocaBanner, 4000);
</script>

</body>
</html>
    
asked by anonymous 23.03.2017 / 11:53

1 answer

0

I've had the same problem developing with Laravel 5, and the solution I found was to use <?= ?> or <?php echo ""; ?> concatenated with JS.

<!DOCTYPE html>
<html lang=pt-br>

<head>
    <meta charset="utf=8">
    <title>Teste</title>

</head>

<body>

<div>
    <img class="destaque1" src="{{ asset('images/banners/00004.jpg') }}">
</div>

<script>
var stringImagensBanners = "<?= $imagensBanners ?>";
var banners = stringImagensBanners.split(",");
var bannerAtual = 0;

function trocaBanner() {
    document.querySelector('.destaque1').src = banners[bannerAtual];
    bannerAtual = (bannerAtual + 1);

    if (bannerAtual == 5) {
    bannerAtual = 0;
    } return false;
}

setInterval(trocaBanner, 4000);
</script>

</body>
</html>
    
23.03.2017 / 17:00