Common mustache template for JS and PHP

634 Views Asked by At

I am using mustache for both JS and PHP, I have created one template for JS now I want to use that template in PHP. Is is possible to reuse that template?

For reference see the below code: JS template:

 <table class="table table-bordered table-hover table-striped tablesorter">
        <thead>
            <tr>
                <th class="header">Name</th>
                <th class="header">Email ID</th>
                <th class="header">Contact Number</th>
                <th class="header">Edit</th>
            </tr>
        </thead>
        <tbody>
        <div id="eTableList"></div>    
        <script id="eList" type="text/template">     
                <tr>
                    <td>{{name}}</td>
                    <td>{{email}}</td>
                    <td>{{contact_number}}</td>
                    <td><a href="{{id}}">View/Edit</a></td>
                </tr>
         </script>    
        </tbody>
    </table>

PHP template:

 <table class="table table-bordered table-hover table-striped tablesorter">
        <thead>
            <tr>
                <th class="header">Name</th>
                <th class="header">Email ID</th>
                <th class="header">Contact Number</th>
                <th class="header">Edit</th>
            </tr>
        </thead>
        <tbody id="eTableList">
                <tr>
                    <td>{{name}}</td>
                    <td>{{email}}</td>
                    <td>{{contact_number}}</td>
                    <td><a href="{{id}}">View/Edit</a></td>
                </tr>
        </tbody>
    </table>

The output of both the templates is same, but I am calling them according to my need using PHP or JS.

So is there a way to use single template instead of above two templates which can be used in both the calls, ie JS and PHP?

1

There are 1 best solutions below

1
Ademir Mazer Jr - Nuno On

Yes you can, since the location of the template is accessible for PHP at server side and Javascript at client side.

You could have the template file at a subfolder of your public access, for example:

public
-- index.php
-- assets
-- -- img (your client side images)
-- -- css (your styles)
-- -- templates
-- -- -- my_template.tpl
-- -- js (your javascript)

Then when you gonna use it in js script, call from relative path ../templates/my_template.tpl, and in PHP, call from absolute path, something like MY_ROOT_APP_CONSTANT . "assets/templates/my_template.tpl"

Hope this help you.

Best regards