Monday, September 15, 2014

[Complete] Mustache Templating in PHP Codeigniter Tutorial

Using templating engine with PHP saves more time when you are working on long time projects.

Eventhough Codeigniter uses uses MVC, Most of the time view looks rubbish.

Templating like Mustache Saves Time, and its easy to upgrade template because most of view logic are present in template files FILENAME.mustache


How to Use Mustache Templating with Codeigniter

Requirements

Prepare Codeigniter
First Download Mustache for PHP Library from above Link.

Save the files inside third_party/Mustache as shown in image.
Mustache PHP in Codeigniter folder

In your Controller function


function testpage() {
            require_once APPPATH.'third_party/Mustache/Autoloader.php';
            Mustache_Autoloader::register();
            $entry = new Mustache_Engine;
            $template = read_file("template/back/listing.mustache");
            $x['listing'] = $this->Accountmodel->get_listing(); //Data from Model as result_array;
            $data['template'] = $entry->render($template, json_decode(json_encode($x),TRUE));
            $this->load->view('front/home',$data);
}


Line 2require_once APPPATH.'third_party/Mustache/Autoloader.php';

This will include the Mustache Autoloader Files with in Codeigniter.

Line 3Mustache_Autoloader::register();   It will Initialize mustache autoloader Class.

Line 4: $entry = new Mustache_Engine; It will create an Class Object from Mustache Library.

Optionally you can pass parameters if you want caching functionality and all. 
$mustache = new Mustache_Engine(array(
    'template_class_prefix' => '__MyTemplates_',
    'cache' => dirname(__FILE__).'/tmp/cache/mustache',
    'cache_file_mode' => 0666, // Please, configure your umask instead of doing this :)
    'cache_lambda_templates' => true,
    'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'),
    'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'),
    'helpers' => array('i18n' => function($text) {
        // do something translatey here...
    }),
    'escape' => function($value) {
        return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
    },
    'charset' => 'ISO-8859-1',
    'logger' => new Mustache_Logger_StreamLogger('php://stderr'),
    'strict_callables' => true,
    'pragmas' => [Mustache_Engine::PRAGMA_FILTERS],
));

Line 5: $template = read_file("template/back/listing.mustache");
This will load the Mustache structure into the Variable $template . read_file is Codeigniter function.

Sample Structure of listing.mustache

          {{#listing}} //Looping in array
<div class="col-xs-12 col-sm-12 col-md-10 col-lg-10">
                <div>
                     <h4>{{title}}</h4>
                       {{description}}<span class="fa fa-lock icon pull-right"> Sold</span>
                </div>

                <div class="clearfix">
                      <div class="pull-left">
                            <span class="fa fa-inr icon"> {{amount}}</span>
                      </div>
                      <div class="pull-right">
                              {{order_completion_period}} | {{end_period}}
                       </div>
                            
                </div> 
          {{/listing}} //End of Looping

Line 6: $x['listing'] = $this->Accountmodel->get_listing();
Returned Date from model function as Array.

Line 7: $data['template'] = $entry->render($template, json_decode(json_encode($x),TRUE));
Perform Rendering of Json data into mustache template file.
As we have array data, we will encode it into json first, then we will json_decode it with condition TRUE.

Thats it.

Read more…

Saturday, September 6, 2014

Summernote WYSWIG Editor PHP Tutorial with Full Code

Web applications still use the classical wyswig editors. In this Responsive Web Era, everyone looking for responsive wyswig editor, compatible with mobile devices also.

SummerNote is an Open source free wyswig editor build to support of Bootstrap theme framework.

Requirements

  1. JQuery
  2. Bootstrap
  3. SummerNote JS & CSS
  4. Fontawesome (Optional)
Create a plain Html File and Paste the Following code and you will get an Responsive Wyswig Editor with Bootstrap 3 support.

I request you to move summernote files to your server, so that it can load faster than Github.

Following is tested in Chrome, Firefox and IE.
Full Featured WysWig Editor

Responsive View on small screen

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<script src="//code.jquery.com/jquery-1.9.1.js"></script> 
  <!-- include libraries BS3 -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
<script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" />
 
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/codemirror.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/theme/blackboard.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/theme/monokai.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/codemirror.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/mode/xml/xml.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/formatting.min.js"></script>
  
<!-- include summernote css/js-->
<link href="include/summernote.css" / rel="stylesheet">
<script src="include/summernote.min.js"></script>
<script>
    $(document).ready(function() {
        $('#summernote').summernote({
            height: 500
        });
    });
</script>
<head>
    <title>Bootstrap WysWig Editor Summernote</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>

<body>
    <div class="container">
            <div class="row">
                <form class="span12" id="postForm" action="/whateveryouwant.php" method="POST" enctype="multipart/form-data" >
                    <fieldset>
                        <legend>MyCodde.Blogspot.com Editor</legend>
                        <p class="container">
                            <textarea class="input-block-level" id="summernote" name="content" rows="18">
                            </textarea>
                        </p>
                    </fieldset>
                    <button type="submit" class="btn btn-primary">Save changes</button>
                </form>
            </div>
    </div>
</body>
</html>


One of the Notable feature of this editor is It supports drag and drop file upload,Image will be instantly converted into base 64. Awesome.

I have tested this in Internet Explorer 7, but style broken. From IE 8 it is working perfectly.

How to add Instant Image Upload inside Editor

Drag and Drop Image Upload Feature in summernote

Replace the above script part with the following code. Now you will get the Instant File Upload inside article, instead of base64.

Use php move_auploaded_file() function to save the uploaded data to your server.

    $(document).ready(function() {
        $('#summernote').summernote({
            height: 200,
            onImageUpload: function(files, editor, welEditable) {
                sendFile(files[0], editor, welEditable);
            }
        });
        function sendFile(file, editor, welEditable) {
            data = new FormData();
            data.append("file", file);//You can append as many data as you want. Check mozilla docs for this
            $.ajax({
                data: data,
                type: "POST",
                url: 'savetheuploadedfile.php',
                cache: false,
                contentType: false,
                processData: false,
                success: function(url) {
                    editor.insertImage(welEditable, url);
                }
            });
        }
    });

savetheuploadedfile.php

<?php

//TODO List
// 1) Rename the File
// 2) For Multiple Upload , Loop through $_FILES
$dir_name = "uploads/";
    move_uploaded_file($_FILES['file']['tmp_name'],$dir_name.$_FILES['file']['name']);
    echo $dir_name.$_FILES['file']['name'];
?>



Thats it.

Read more…