CodeIgniter helper in the view

2019-06-20 07:53发布

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);

3条回答
The star\"
2楼-- · 2019-06-20 08:27
get_instance()->load->helper('HELPER_NAME');
查看更多
Explosion°爆炸
3楼-- · 2019-06-20 08:33

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.

查看更多
The star\"
4楼-- · 2019-06-20 08:34

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);
查看更多
登录 后发表回答