Search code examples
javascriptjqueryjoomla

How can i add inline script in joomla 3?


I'm trying to add script in my teplate but it often gives an error:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in Z:\home\localhost\www\RealEstate\templates\real_estate\index.php on line 21

This is my code:

<?php

defined('_JEXEC') or die;

$app             = JFactory::getApplication();
$doc             = JFactory::getDocument();
$user            = JFactory::getUser();
$this->language  = $doc->language;
$this->direction = $doc->direction;

$params = $app->getTemplate(true)->params;


$doc->addStyleSheet('templates/' . $this->template . '/css/swiper.min.css');
$doc->addStyleSheet('templates/' . $this->template . '/css/style.css');

JHtml::_('jquery.framework');
$doc->addScript('templates/' . $this->template . '/js/swiper.min.js');
$doc->addScriptDeclaration('
  jQuery(document).ready(function() {
   var swiper = new Swiper('.swiper-container', {
   nextButton: '.swiper-button-next',
   prevButton: '.swiper-button-prev',
   pagination: '.swiper-pagination',
   slidesPerView: 3,
   slidesPerColumn: 2,
   paginationClickable: true,
   spaceBetween: -15,
   });
});
');

?>

I'm also trying this:

JHtml::_('jquery.framework', false);
$doc->addScript('templates/' . $this->template . '/js/swiper.min.js');
$doc->addScriptDeclaration('
  $(document).ready(function() {
   var swiper = new Swiper('.swiper-container', {
   nextButton: '.swiper-button-next',
   prevButton: '.swiper-button-prev',
   pagination: '.swiper-pagination',
   slidesPerView: 3,
   slidesPerColumn: 2,
   paginationClickable: true,
   spaceBetween: -15,
   });
});
');

Neither doesn't work but gives an error. Would you please guys shed light on what i'm doing wrong.


Solution

  • You are concatenating string in a wrong way

    Put that script inside double-quotes

    $doc->addScriptDeclaration("
      jQuery(document).ready(function() {
       var swiper = new Swiper('.swiper-container', {
       nextButton: '.swiper-button-next',
       prevButton: '.swiper-button-prev',
       pagination: '.swiper-pagination',
       slidesPerView: 3,
       slidesPerColumn: 2,
       paginationClickable: true,
       spaceBetween: -15,
       });
    });
    ");