1

I want to define a new phtml block in the head of my module: I try to add something like this in my app/code/Custom/Module/view/frontend/layout/default.xml file:

<?xml version="1.0"?>
<page xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <body>
        <referenceBlock name="head.additional">
            <block class="Custom\Module\Block\Hello" name="mycustom" template="Custom_Module::mycustom.phtml" />
        </referenceBlock>
    </body>
</page>

the phtml file must be loaded in the head and in the phtml file I have only a small javascript that will call a slider.

$('.slideshow').banner({image :"images/slide1.png"});

How I can create Custom\Module\Block\Hello block and what must contain this file?

Thank you

UPDATE:

<script  type="text/javascript">       
    require([
        'jquery', 
        'banner'
    ], function($, banner){
        $(function(){
           $(document).banner({});
        })
    });
</script> 



<div class="snowme">Text me</div>
2

Create Custom module block with at least contain this code(Path: app\code\Custom\Module\Block):

<?php

namespace Custom\Module\Block;

class Hello extends \Magento\Framework\View\Element\Template
{    
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }
}

Add below script into your phtml file to call slider js:

<script  type="text/javascript">       
    require([
        'jquery', 
        'banner'
    ], function($, banner){
        $(function(){
            $('.slideshow').banner({image :"images/slide1.png"});       
        })
    });
</script> 

Define requirejs-config.js file contains below code:

var config = {
    paths: {            
         'banner': "Custom_Module/js/sliderjs.js"
      },   
    shim: {
        'banner': {
            deps: ['jquery']
        }
    }
}

Add your js file into view/frontend/web/js folder.

Note: If you have error like "jquery is not a function" add below code into your js

require([ 'jquery', 'jquery/ui'], function($){
    $(document).ready(function($) {
      //banner js code
    });  
});
|improve this answer|||||
  • thank you that js is not work very well I read and must be declared like this: jQuery(document).ready(function(){ jQuery(document).banner( – Robert Nov 28 '17 at 11:32
  • you have any idea what is wrong? – Robert Nov 28 '17 at 11:32
  • What is the exact issue? – Ronak Chauhan Nov 28 '17 at 11:34
  • Block issue or js declaration issue? – Ronak Chauhan Nov 28 '17 at 11:34
  • I really don't know I think is a js declaration – Robert Nov 28 '17 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.