在视图内加载视图时,如何获取主视图的名称?
Got it, let's break down why your current approach isn't working first, then walk through straightforward, reliable fixes.
Why pathinfo(__FILE__) and $_ci_view return internal.php
__FILE__is a PHP magic constant that always points to the current file being executed. Since you’re running this line insideinternal.php, it will naturally return that file’s name.$_ci_viewis a variable CodeIgniter injects into the current view file, and it’s set to the name of the view being loaded at that exact moment. Again, that’sinternal.phpwhen you’re working in that file.
Fix 1: Pass the parent view name explicitly (most maintainable)
The simplest and most reliable way is to pass the main view’s name to internal.php when you load it from main.php. You can even dynamically fetch the main view’s filename so you don’t have to hardcode it (handy if you ever rename main.php):
In main.php:
// Dynamically get the current main view's filename $parent_view_name = pathinfo(__FILE__, PATHINFO_FILENAME); // Load internal.php and pass the parent view name as a variable $this->load->view('internal', ['parent_view' => $parent_view_name]);
Then in internal.php, just echo the passed variable:
echo $parent_view; // Outputs "main"
Fix 2: Set the parent view name in the controller
If you want to manage this at the controller level (useful if you have multiple main views), set the main view name in your controller and pass it down through the view chain:
In your controller:
$data['main_view_name'] = 'main'; // Or dynamically fetch it if needed $this->load->view('main', $data);
In main.php:
// Pass the main view name to internal.php $this->load->view('internal', ['parent_view' => $main_view_name]);
In internal.php:
echo $parent_view; // Outputs "main"
Fix 3: Use CodeIgniter's Loader class (advanced, CI3-specific)
If you don’t want to pass variables manually, you can tap into CodeIgniter’s Loader class to check loaded views. Note this relies on internal CI properties, so it’s less maintainable across versions:
In internal.php:
// Get the CodeIgniter instance $CI =& get_instance(); // The Loader tracks loaded views in the $_ci_loaded_files array $loaded_views = $CI->load->_ci_loaded_files; // Find internal.php in the list and grab the previous entry (main.php) $internal_path = APPPATH . 'views/internal.php'; $internal_index = array_search($internal_path, $loaded_views); if ($internal_index !== false && $internal_index > 0) { $parent_view_path = $loaded_views[$internal_index - 1]; $parent_view_name = pathinfo($parent_view_path, PATHINFO_FILENAME); echo $parent_view_name; // Outputs "main" }
内容的提问来源于stack exchange,提问作者ITSagar

