Search code examples
codeignitercodeigniter-4

Where to load View Parser service in Codeigniter 4


I am not understanding loading the parser service in Codeigniter 4, Please tell me how to load and where to load it, and how can i use it in View.


Solution

  • Load the parser inside of the controller method that you want to use it in e.g. inside of index() method of Home controller. You may load it using $parser = \Config\Services::parser(); or $parser = service('parser');.

    Rendering a view can be done by echoing as follows:

    echo $parser->setData($data)->render($view);
    

    wherein $data can be something like ['blog_title' => 'My Blog Title', 'blog_heading' => 'My Blog Heading']; and $view is the address of your view file inside of /Views directory.

    This will then replace any 'substitutions' in view file such as <h1>{blog_title}</h1> with your data. You can read more about the specifics of substitutions in docs.

    Note: Using the Parser, your view templates are processed only by the Parser itself, and not like a conventional view PHP script. PHP code in such a script is ignored by the parser, and only substitutions are performed.