本文介绍了如何将脚本和 CSS 挂钩到 <head> 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作的模块的事情是它会生成一个 javascript 片段,所以我不能使用一个动作来将它挂接到 HTML 的部分,因为该动作要求我有一个 JS 文件(纠正我如果我错了).有哪些方法可以让我将 JavaScript 片段放入标签中?我正在考虑使用块,但我不确定块应该附加在什么之后,我必须考虑这将适用于所有主题.

The thing with the module I am making is that it kind of generates a javascript snippet, so I cannot use an action to just hook that into the section of the HTML since the action requires that I have a JS file (correct me if I am wrong). What are some ways for me to put a JavaScript snippet into the tag? I was thinking of using a block, but I am not sure what the block should be appended after and I have to consider that this will work with all themes.

推荐答案

股票头部模板为

template/page/html/head.phtml

在您自己的主题中复制该文件将是获得一些 javascript 的最简单方法.

Copying that file in your own theme would be the simplest way to get some javascript in the head.

虽然更好(从开发人员的角度来看),该模板包含以下行

Better though (from a developer point of view), this template includes the following line

<?php echo $this->getChildHtml() ?>

about 链接打印出一个块的所有子块.因此,将子块添加到头块也可以.

The about link prints out all the child blocks of a block. So, adding a child block to the head block would also work.

<layouts>
    <default> <!-- does this to all pages — use specific layout handles to target a page -->
        <reference name="head"> <!-- get a reference to the existing head block -->
            <block type="core/text" name="simple_example_javascript_block"> <!-- append a simple text block, probably better to use a new template block -->
                <action method="setText"> <!-- set our new block's text -->
                    <text><![CDATA[
                    <script type="text/javascript">
                        alert("foo");
                    </script>
                    //]]></text>
                </action>
            </block>
        </reference>
    </default>
</layouts>

上述 XML 使用一个简单的 core/text 块将 javascript 添加到每个 Magento 页面.从 local.xml 工作,应该在其他地方工作.我确信应该会想到更好的方法(例如模板块)

The above XML uses a simple core/text block to add javascript to every Magento page. Works from local.xml, should work elsewhere. I'm sure better ways to do this should spring to mind (template block, for example)

这篇关于如何将脚本和 CSS 挂钩到 <head> 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 22:36