PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 2, 2022

[FIXED] How to make a custom script tag for Html in Cake Php

 February 02, 2022     cakephp, cakephp-2.x, javascript, php     No comments   

Issue

I'm trying to import a js file as type module in CakePHP 2.10.22. You can do something like this

echo $this->Html->script('test', array('inline' => false, 'type' => 'module'));

but that results in the tag being like <script type="text/javascript" type="module">

I also tired

echo $this->Html->tag(
    'script',
    null,
    array(
        'type' => 'module',
        'src' => '/test/js/objects/test.js'
    )
);

But it does not put it inside of the head html tag.

Is there a way to add on or make a custom helper that will add it into the head?


Solution

When using the HTML helper, one option would be to customize the template that is used for generating the script tag, that is javascriptlink, which by default has the type attribute hard coded:

// in app/Config/html_tags.php
$config = array(
    'tags' => array(
        'javascriptlink' => '<script src="%s"%s></script>',
        // ...
    ),
);
// in your view layout or template
$this->Html->loadConfig('html_tags');

// or in your (App)Controller
public $helpers = array(
    'Html' => array(
        'configFile' => 'html_tags',
    ),
);

This would then require that you always specify a type for your script tags in case needed.

Another option would be to generate custom tags as shown in your question, and use the view's append() method to add it to the respective view block that renders in your layout, by default that would be the block named script:

$scriptTag = $this->Html->tag(/* ... */);
$this->append('script', $scriptTag);

This could certainly be implemented in a custom/extended HTML helper if you wanted to.

See also

  • Cookbook > Views > Helpers > HtmlHelper > Changing the tags output by HtmlHelper
  • Cookbook > Views > Using view blocks
  • Cookbook > Views > Helpers > Creating Helpers
  • Cookbook > Views > Helpers > Using and Configuring Helpers


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing