Codeigniter - 在特定视图上加载特定的JS库

问题描述:

我要加载google maps API ie:

I'm trying to load the google maps API ie:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">

但是因为我只有一个页面上有谷歌地图(我宁愿没有为所有文件加载API),我如何将消息从控制器发送到视图,我想加载这个特定的JS文件?

in my head template. But because I've only got one page with a google map on it (I'd rather not have the API load for all files), how would I send the message from the controller through to the view that I wish to load this particular JS file?

感谢您的帮助。

是使用具有javascript / css注入的模板库 - 参见:

One solution is to either use a template library that has javascript/css "injection" - see:

http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html#utilities

$this->template->add_js('js/jquery.js');
$this->template->add_js('alert("Hello!");', 'embed');

了解更多信息。

不想使用模板库,做这样的事情:

If you don't want to use a template library, do something like this:

*假设在地图控制器,并且你需要的JS文件在默认页面

*assuming on the "Map" controller, and that you need the JS file on the default page.

class Map extends CI_Controller {

    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        $scripts = array(
    '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">' . "\n", 
    '<script>something</script>');
       /* this method lets you add multiple...*/

        $data['scripts'] = $scripts;
        $this->load->view('my_map/index', $data);
    }
}

b

if(isset($scripts))
{
    foreach($scripts as $script)
    {
        echo $script;
    }
}

本质上你构建一个脚本文件/ css文件(无论什么),然后检查它的存在并将其转储到视图的部分。

essentially you build an array of script files/css files (whatever), then check for its prescence and dump it in the head section of your view.

d个人为模板选项。

另请注意,CI2.0有一个新的 javascript驱动程序可能值得一读

Also note CI2.0 has a new javascript driver might be worth a read