Kyle Cronin
Kyle Cronin

Reputation: 79103

CodeIgniter doesn't like methods in views?

I'm playing around with CodeIgniter; hoping to convert some of my old, ugly PHP into a more maintainable framework. However, I've come across a rather frustrating roadblock - I can't seem to define methods in my views. Any time I try I get a completely blank page, and when I look in the debug log the processing seemed to stop after the view was loaded. Can I define methods within views? If not, why, and what workarounds would you suggest?

Note: The method has to do with formatting output strings.

Upvotes: 2

Views: 2188

Answers (3)

Vova Popov
Vova Popov

Reputation: 1063

Views are not meant to call controller actions. Reverse your logic, call that function in the controller and set it to a variable you sent to the view. Then you can have the if statement check that variable in your view template.

If that doesn't work for you, maybe a helper is what you need: http://codeigniter.com/user_guide/general/helpers.html

Upvotes: 0

Christian Davén
Christian Davén

Reputation: 18117

Define your functions in a helper and load them from the controller. That way you can reuse the functions in other views, as well.

Upvotes: 11

Josh
Josh

Reputation: 1479

I'm not familiar with CodeIgnitor, but it could be including your templates multiple times. Try wrapping your function in a check:

if (!function_exists('myfunc'))
{
    function myfunc() {}
}

CodeIgnitor is probably swallowing errors, so you could also try flushing buffers immediately before your function:

while(ob_end_flush()){}
error_reporting(E_ALL);
ini_set('display_errors', 1);

In reality though, you should probably make your string formatting code a bit more general. Your template is not really a good place to start adding functions. You'll begin duplicating code, and it defeats the purpose of having templates at all. I'd suggest experimenting with CodeIgnitor's Helpers and Plugins

Upvotes: 0

Related Questions