anonym
anonym

Reputation: 4850

How do I use this seemingly simple loop in CodeIgniter's view?

In the view, right before the footer, I want to load three JavaScript files. So, the controller sets three variables. For example, $js_1 = "bootstrap.js", $js_2 = '' and $js_3 = "tinymce.js", which may or may not be empty. The logic is, it should echo only if the variable is not empty. I also want to use the ternary if operator.

This was the best I could try.

for ($i = 1; $i <= 3; $i++)
{
    echo (!empty ('$js_' . $i)) ? get_jscript('$js_' . $i) : NULL;
}

The function get_jscript() simply returns the HTML script src.

function get_jscript($js) 
{
    return '<script type="text/javascript" src="' . $js . '"></script> ';
}

Please note that I intend to ask this question to primarily learn the correct PHP syntax and not just load JS in the view.

Upvotes: 0

Views: 64

Answers (3)

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

for ($i = 1; $i <= 3; $i++)
{
    if(!empty($js.'_'.$i)){ echo get_jscript($js.'_'.$i); echo "</br>";}
}

function get_jscript($js) 
{
    return '<script type="text/javascript" src="' . $js . '"></script> ';
}

Upvotes: 0

Sachin Shukla
Sachin Shukla

Reputation: 1279

if you can create a array like this->

$javascript = array('js_1' => "bootstrap.js", 'js_2' => '', 'js_3' = "tinymce.js");

then in your view you have to just call a method

loop_javascript($javascript);

it's better to create a function in codeigniter helper and call that helper in controller's function (check how to use helpers in codeingiter) https://ellislab.com/codeigniter/user-guide/general/helpers.html->

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('loop_javascript'))
{
    function loop_javascript($jscript_array)
    {
        foreach($jscript_array as $key =>$value){
            if($value != ''){
                echo '<script type="text/javascript" src="' . $value. '"></script>';
            }
        }
    }   
}

Upvotes: 3

Brian Ray
Brian Ray

Reputation: 1492

This has some great info on how to use variable variables.

for ($i = 1; $i <= 3; $i++)
{
    echo (!empty (${'js_'.$i})) ? get_jscript(${'js_'.$i}) : NULL;
}

Upvotes: 1

Related Questions