CodeIgniter helper in the view

怎甘沉沦 提交于 2019-12-23 09:19:30

问题


Is it a good workaround and would it be possible to use helper classes in the view, in CodeIgniter. I have a situation when I have to extract with regulars expression from a text couple of strings and generate outputs on matches. I would not like to do this directly in the view and I would like to use for this purpose a helper.

application
--view
---myview.php

and here I should call the helper and return results

for example I want to extract from the text the type of processor, than I pass the text and get returned the processor type. This one is needed because all the data in the view are generated by an API dynamically.

echo $myhelper->processor($text);

回答1:


get_instance()->load->helper('HELPER_NAME');



回答2:


CodeIgniter's user guide explains that helpers can be loaded and their function used in views.

CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views.

However it is not best pratice to load a helper in a view, so you could either auto-load the relevant helper, or load it in your controller(s).

A helper can be loaded anywhere within your controller functions (or even within your View files, although that's not a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so that they become available automatically in any function, or you can load a helper in a specific function that needs it.

So, using helper functions in a view is fine, although it is encouraged that the helper is loaded in a controller, or auto-loaded.




回答3:


Just load the helper in your controller, then

$this->load->helper('MY_common_functions');
$template['content'] = $this->load->view('your_view');

In the view call your function name directly. In this case I called my convertor function

echo convertor($params);


来源:https://stackoverflow.com/questions/16510348/codeigniter-helper-in-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!