I want to cache most of my controllers’ output, but some of the pages need to have links so I can add and edit the info. If I set up a “js” controller and routed “global.js” to a “global” method of a “js” controller, couldn’t I use PHP to dynamically add some JavaScript to “global.js” only if I’m logged in as an admin? Is there a 开发者_开发知识库better way to only cache pages if the visitor is not an admin?
I want to show add/edit/delete links on a page, but only if I'm logged in as an admin. I also want to cache the page. CodeIgniter's caching doesn't support conditional caching, so I needed a workaround to insert the links dynamically. I'm using PHP to dynamically write JavaScript so I can use jQuery to insert the links.
1) I set this in /config/routes.php:
$route['js/global.js'] = 'js/global_scripts'; // function can't be called "global" since it's a PHP keyword
2) Then I have this function in my js controller:
public function global_scripts() {
$this->output->set_header("content-type: application/x-javascript")
$this->load->view('js/global'); // see below
} // global_scripts
3) And this is the js/global view:
$(document).ready(function(){
<?php if($this->is_admin == TRUE): ?> // from my auth + MY_Controller
alert("you're an admin"); // or whatever JS I want
<?php endif; ?>
});
In my view files I have a regular JavaScript link:
<script src="/js/global.js"></script>
If I visit the page and I'm logged in as an admin, I get an alert, and I don't get an alert if I'm not logged in as an admin. So now I can have the script insert add/edit/delete links only if I'm logged in.
精彩评论