What’s the best way to call files?

Asked

Viewed 906 times

3

Well, I use codeigniter (but not specifically in it, anyone who is MVC). I wanted to know the best way to call my files, css, js, fonts, etc. I think the best way is to call in the controller method, but let’s assume that for each page(method) I want to use a certain plugin Js code but not in the other, as I would do?

One day I made some conditionals (php), checking if the URI (controller name) is such load such file(css, js, etc), and this in the footer.php of my template. In this case this would be the best alternative?

Thank you!

  • 1

    You can make a template structure, where you would have a base template (menu, footer and the required Imports) and others would include it and any other additional Imports.

2 answers

1


His basic idea of conditioning by the name of controller is correct (in my opinion), but the execution can be improved. Use file_helper.php to help execute the task. It’s relatively simple: extend the helper in the form indicated in documentation:

Create My_file_helper.php in application/helpers/ and put the next one inside:

if(!function_exists('js_loader')){

/**
* Carrega os scripts por demanda, a depender do controller ativo e do 
* diretorio definido
* @return string
*/
function js_loader() {
    //Captura a instancia do CI
    $ci = & get_instance();
    //Captura o controller ativo
    $controller = $ci->router->fetch_class();
    //Declara o diretorio onde estao os scripts do $controller. 
    //Este diretorio precisa estar acessivel ao navegador
    $jsdir = "assets/js/$controller/";
    //Checagem do $jsdir
    if(file_exists($jsdir)){
        $DirectoryIterator = new DirectoryIterator($jsdir);
        echo "<!--Scripts do controller $controller-->\n";
        foreach ($DirectoryIterator as $entry) {
            //Carrega apenas arquivos (exclui diretorios...)
            if ($entry->isFile()) {
                //Carrega apenas arquivos '.js'
                if (in_array($entry->getExtension(), ['js'])) {
                    $file = base_url($jsdir.$entry->getFilename());
                    echo "<script src='$file' charset='UTF-8'></script>\n";
                }
            }
        }
    }
   }
}

Load the helper in the instance of Codeigniter (or use autoload) and call the function anywhere in the view:

<?php $this->load->helper('file'); ?>
 <html>
  <body>
   <?= js_loader() ?>
  </body>
</html>

Basically: all . js scripts inside "assets/js/$controller/" will be loaded when $controller is active.

0

The best practice would be to leave the resource calls in the View, as it is to her that they will serve.

Just like @leonardopessoa commented on your question, you can create templates that provide common parts to the main template, for example:

application/views/header.php

<!DOCTYPE html>
<html>
<head>
    <title>Hello World - Template</title>
    <link rel="stylesheet" href="folha_de_estilo_main_para_todos.css">
</head>
<body>

Applications/views/footer.php

    <script src="script_main_para_todos.js"></script>
</body>
</html>

Applications/views/page_personal.php

<p>
    Hello world - Template do método personal!
</p>

Applications/views/page_contact.php

<p>
    Hello again, world - Template do método contact!
</p>
<script src="script_customizado_apenas_para_este_template.js"></script>

Applications/controllers/pages.php

class Pages extends CI_Controller {
 
public function index() 
    {
        $this->load->view('header');
        $this->load->view('page_personal');
        $this->load->view('footer');
    }
}

public function contact() 
    {
        $this->load->view('header');
        $this->load->view('page_contact');
        $this->load->view('footer');
    }
}

Well, I believe that there is no ideal way, but in my opinion, this would be the best way to organize resources in an MVC application, mainly applications with Codeigniter, which does not provide such cool helpers so to do this.

I used code snippets of the following link to write this answer, in it can be found another way to implement templates in CI, but I did not find anything interesting: https://code.tutsplus.com/tutorials/an-introduction-to-views-templating-in-codeigniter--net-25648

  • 1

    Hasty response. This is not structure of templates in the Codeigniter. Structure of templates is this here. You gave a reference in your reply but did not follow it.

  • Well, without using extra features, it’s a template structure, don’t stick to names, reading the IC documentation, there’s nothing to work with templates that way and it’s something quite different.

  • No, it’s not. And you didn’t use the documentation from CI as a reference. And even if you used the IC reference, your answer would still be loading several views, and no use of template. Have you read the reference you indicated? Read the part "Templating in Codeigniter". Note: the official documentation does have a way of working with templates ;)

  • ahuaha... man... if you really want to help with the best answer, put it here. If it applies what I went through, I’m sure it will get the expected result and not so far from what is applied in other frameworks, you have the word "Template" in your head and it’s getting in the way. Want to do things the right way? Use a mature framework that doesn’t invent as much fashion as the IC. Seriously, is that lib a better alternative? And if there is such secret documentation about something that the IC has no support, put it here. HELP THE COMMUNITY

  • just for the record: it was you who gave the reference, and the "secret" documentation is in the comment.

  • CI Template Documentation (single snippet): The Template Parser Class can perform simple text substitution for pseudo-variables contained Within your view files. It can parse simple variables or variable tag pairs. Last line of the template lib load method: $this->ci->load->view('templates/'.$tpl_name, $data); . Thanks for the feedback, but they were unnecessary.

  • They were useful to prove at least one thing: you do not know what you are saying in your reply. Note that, according to the documentation, if in blog_template.php our little friend declare the right variables, just call the corresponding files in array $data in $this->parser->parse('blog_template', $data);, and not keep calling a lot of views at the same time. Translation: is not the same thing ;)

  • That’s why the stack doesn’t recommend "discussions," but anyway, @Adrianofernandes I do exactly what you did in your controller, header after page after footer, but my JS calls were all in the footer, and even when I didn’t need the code, There was that heap of <script src>, you know? Shutupmagda I’ve done so too, a layout (view) where you have the variable header and footer, both were called in the view by the variable that was passed in the controller and not a lot of views being called in the controller, but still forced to all!

  • Note that at no point did I say that his answer was no good, I just said that he confused the concepts. It is relatively easy to load only the methods you set for a controller. Just use a helper. I’ll give you an answer here later...

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.