How to Determine if a View File Is Available in CakePHP

Asked 2 years ago, Updated 2 years ago, 69 views

Is there a way to determine if CakePHP has a view file?

I'd like to separate what to do with or without a view file.

cakephp

2022-09-30 10:29

3 Answers

App::path('View')

You can use the above code to get the view path anywhere.(Return value is array)
If you have a file, can you connect the required view file names and file_exists from there?

Reference URL: http://book.cakephp.org/2.0/ja/core-utility-libraries/app.html#app-path

Specifically, provide an example of the return value for App:path('View'); in CakePHP 2.x series.

Prerequisites

App/Config/core.php contains the following sentence:

App::build(array('View'=>array(APP.'ViewSmartPhone/'));

Please read the absolute path and URL accordingly according to your environment.

Display Code

App/Controller/TopsController.php

public function index()
{
    var_dump(App::path('View'));
}

Display Results

URL:ttp://example.com/tops/index

array(size=2)
  0=>string'/var/www/app/ViewSmartPhone/'(length=52)
  1=>string'/var/www/app/View/' (length=42)

Practical samples

I think it would be good to connect the controller name and the expected view name as follows.
If you write the code below where you want to find out if the intended .ctp file exists, you should be able to execute it.

$views_path=App::path('View');
foreach($views_pathas$path){
    $_viewpath=$path.'Tops'.DS.'index.ctp';
    if(file_exists($_viewpath){
        // What to do if a file exists.
    } else{
        // What to do if the file does not exist
    }
}


2022-09-30 10:29

I'm curious why it was handled like that...
I can use the code below to get the absolute path of the view file, so I think I can check the file utility properly.

APP. 'View'.DS.$this->viewPath.DS.$this->view

Also, if you used a theme, we have not verified it.


2022-09-30 10:29

App::path('View')
It can be solved by


2022-09-30 10:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.