I just learned about moustache.js and i am attempting to create an HTML template. However, the documentation is a bit hard to decipher. I found a good site that explains partials (which I believe I will need). I was hoping someone might be able to just 'get me started' on how I would need to do this.
I have a php file that I need to convert to the template:
PHP:
<div id='board'>
<?php
if ($threads)
{
$count = count($threads);
$perpage = 17;
$startlist = 3;
$numpages = ceil($count / $perpage);
if ($page == 'home') {$page = 1;}
$threadstart = ($page * $perpage) - $perpage;
$i = 0;
echo "<table class='board'>
<tr>
<th width='5%'><img src='".base_url()."img/board/icons/category_icon.png' alt='category_icon'/></th>
<th width='5%'>Tag</th>
<th width='50%'>Subject</th>
<th width='7.5%'>Author</th>
<th width='7.5%'>Replies/Views</th>
<th width='15%'>Last Post</th>
</tr>";
foreach ($threads as $list)
{ $i++;
$thread_owner = $this->thread_model->get_owner($list['owner_id']);
$thread_id = $list['thread_id'];
$query = $this->db->query("SELECT f.tag FROM filter_thread AS ft
INNER JOIN filter AS f ON ft.filter_id = f.filter_id
WHERE thread_id = $thread_id");
$result = $query->result_array();
$trunc_body = $this->thread_model->get_reply_summary($thread_id);
$filter = "";
$filter2 ="";
$ent = "entertainment";
foreach ($result as $string)
{
if ($string['tag'] == $ent) {
$filter2 .= "<div id='entertainment'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/entertainment_icon.png' title='Entertainment' alt='Entertainment'/>";
$filter2 .= "</p></div>";
} else {
$filter2 .= "<div id='misc'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/misc_icon.png' title='Misc' alt='Misc'/>";
$filter2 .= "</p></div>";
$filter .= " [".$string['tag']."]";
}
}
if (!$result) { $filter = "" AND $filter2 =""; }
if ($i > $threadstart AND $i <= $threadstart + $perpage)
{
echo "<tr>";
echo "<td>".$filter2."</td>";
echo "<td>".$filter."</td>";
echo "<td title='".$trunc_body['0']['body']."'>".ucfirst($list['subject'])."<div id='filter'><p></p></div></td>";
echo "<td><p>".$thread_owner."</p></td>";
echo "<td align='right'>Replies: ".$list['replies_num']."<br>Views: ".$list['views']."</td>";
$owner = $this->thread_model->get_owner($list['last_post_id']);
echo "<td>".$owner." <br>".$list['replystamp'] ."</td></tr>";
}
}
echo "</table>";
echo "<br>";
echo "Current Page: $page | ";
echo "Page: ";
for ($n = 1; $n < $numpages+1; $n++)
{
echo "<a href=".base_url()."main/home/$n>$n</a> | ";
}
}
?>
</div>
And here is the AJAX
$(function() {
$('#all').addClass('ui-selected')
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
url: 'updatefilters',
dataType: 'json',
data: { filters: filters },
success: function(data){
var template = "<div id ='board'>TESTING{{#body}}<table>";
var partials = "{{#subject}}";
//for (i=0 ; i< data.length ; i++)
//{html += "<tr><td>" + data[i].subject + "</td><td>" + data[i].body + "</td></tr>";}
//html += "</table></div>";
var html = Moustache.to.html(template, data, partials);
$('#board').html(html);
}
});
}
});
Im not sure how to navigate through the JSON array with moustache..and as it is, it does not update the page, though the commented out parts DO.
Thanks in advance!
First of all if you are receiving a json string you will need to to parse it (use $.parseJSON(data))
Once you have the data parsed you need to loop throught the JSON attributes.
For example:
If JSON has the following: body: {content: [dataObj:{data:'a'}, dataObj[data:'b']]}
do
<div>{{#body}}<div>
<div>{{#content}}<div>
<div>{{#dataObj}}<div>
<span>{{data}}<span>
If you are using partial, you will need to call them inside the main template.
Check the moustache5 documentation, it has improved a lot.
Related
i'm try to create trial balance i somehow achieve tree view in my array and now i want to print my code but don't know how to make tree because i don't know how many children i can get in future and i'm not very good at recursion below is my tree prepared array and i also attach my result that i can make via foreach loop but stuck in children node i can make children nodes via foreach but the problem is it's not a best approach to follow so please help me out to print my tree structure data as per my array. Any help would be appreciated.
Here my tree array look like : Tree Array
My result look like this this is only root nodes of an array and i using jstree to show hierarchy.
<?
$total_opening_debit = 0;
$total_opening_credit = 0;
$total_debit = 0;
$total_credit = 0;
foreach($this->trees as $key => $value)
{
foreach($value as $tree)
{
if($tree["id"] != "")
{
?>
<li>
<span class="first"><? echo $tree["name"]; ?></span>
<span class="other">
<?
if ($tree["opening_debit"] > $tree["opening_credit"])
{
echo format_currency($tree["opening_debit"] - $tree["opening_credit"], 2) . " Dr.";
}
elseif ($tree["opening_credit"] > $tree["opening_debit"])
{
echo format_currency($tree["opening_credit"] - $tree["opening_debit"], 2) . " Cr.";
}
else
{
echo "0";
}
$total_opening_debit += $tree["opening_debit"];
$total_opening_credit += $tree["opening_credit"];
?>
</span>
<span class="other">
<?
if($tree["period_debit"]<>"" && $tree["period_debit"]<>"0")
{
echo format_currency($tree["period_debit"], 2);
$total_debit += $tree["period_debit"];
}
else
{
echo 0;
}
?>
</span>
<span class="other">
<?
if($tree["period_credit"]<>"" && $tree["period_credit"]<>"0")
{
echo format_currency($tree["period_credit"], 2);
$total_credit += $tree["period_credit"];
}
else
{
echo 0;
}
?>
</span>
<span class="other">
<?
if ($tree["opening_debit"] + $tree["period_debit"] > $tree["opening_credit"] + $tree["period_credit"])
{
$closing = format_currency($tree["opening_debit"] + $tree["period_debit"] - $tree["opening_credit"] - $tree["period_credit"], 2) . " Dr.";
}
elseif ($tree["opening_credit"] + $tree["period_credit"] > $tree["opening_debit"] + $tree["period_debit"])
{
$closing = format_currency($tree["opening_credit"] + $tree["period_credit"] - $tree["opening_debit"] - $tree["period_debit"], 2) . " Cr.";
}
else
{
$closing = "0";
}
echo $closing;
//calculate all opeing and closing debit & credit.
if ($tree["opening_debit"] + $tree["period_debit"] > $tree["opening_credit"] + $tree["period_credit"])
{
$total_closing_debit += ($tree["opening_debit"] + $tree["period_debit"] - $tree["opening_credit"] - $tree["period_credit"]);
}
if ($tree["opening_credit"] + $tree["period_credit"] > $tree["opening_debit"] + $tree["period_debit"])
{
$total_closing_credit += ($tree["opening_credit"] + $tree["period_credit"] - $tree["opening_debit"] - $tree["period_debit"]);
}
?>
</span>
<?
if(count($tree["children"]) > 0)
{
//make_children_tree();
}
?>
</li>
<?
}
}
}
?>
i solved myself here what approach i choose i extract children array into other array and on that array i use my recursion to do magic.
<? $array = $trial_tree["children"]; ?>
$trial_balance_tree = $this->trees;
$total_opening_debit = 0;
$total_opening_credit = 0;
$total_debit = 0;
$total_credit = 0;
$total_closing_debit = 0;
$total_closing_credit = 0;
$total_opening = 0;
$total_closing = 0;
function makeListItems($a) {
global $total_opening_debit,$total_opening_credit,$total_credit,$total_debit,$total_closing_debit,$total_closing_credit,$total_opening,$total_closing;
$out = '';
foreach($a as $val) {
//print_r($key); echo is_array($val);exit;
if($val["id"] > 0)
{
$out .= '<li>';
$out .= "<span class='first'>" . $val["name"] . "</span>";
$out .= "<span class='other'>";
if ($val["opening_debit"] > $val["opening_credit"])
{
$out .= format_currency($val["opening_debit"] - $val["opening_credit"], 2) . " Dr.";
}
elseif ($val["opening_credit"] > $val["opening_debit"])
{
$out .= format_currency($val["opening_credit"] - $val["opening_debit"], 2) . " Cr.";
}
else
{
$out .= "0";
}
$total_opening_debit += $val["opening_debit"];
$total_opening_credit += $val["opening_credit"];
$out .= "</span>";
$out .= "<span class='other'>";
if($val["period_debit"]<>"" && $val["period_debit"]<>"0")
{
$out .= format_currency($val["period_debit"], 2);
$total_debit += $val["period_debit"];
}
else
{
$out .= 0;
}
$out .= "</span>";
$out .= "<span class='other'>";
if($val["period_credit"]<>"" && $val["period_credit"]<>"0")
{
$out .= format_currency($val["period_credit"], 2);
$total_credit += $val["period_credit"];
}
else
{
$out .= 0;
}
$out .= "</span>";
$out .= "<span class='other'>";
if ($val["opening_debit"] + $val["period_debit"] > $val["opening_credit"] + $val["period_credit"])
{
$closing = format_currency($val["opening_debit"] + $val["period_debit"] - $val["opening_credit"] - $val["period_credit"], 2) . " Dr.";
}
elseif ($val["opening_credit"] + $val["period_credit"] > $val["opening_debit"] + $val["period_debit"])
{
$closing = format_currency($val["opening_credit"] + $val["period_credit"] - $val["opening_debit"] - $val["period_debit"], 2) . " Cr.";
}
else
{
$closing = "0";
}
$out .= $closing;
//calculate all opeing and closing debit & credit.
if ($val["opening_debit"] + $val["period_debit"] > $val["opening_credit"] + $val["period_credit"])
{
$total_closing_debit += ($val["opening_debit"] + $val["period_debit"] - $val["opening_credit"] - $val["period_credit"]);
}
if ($val["opening_credit"] + $val["period_credit"] > $val["opening_debit"] + $val["period_debit"])
{
$total_closing_credit += ($val["opening_credit"] + $val["period_credit"] - $val["opening_debit"] - $val["period_debit"]);
}
$out .= "</span>";
if(array_key_exists('children', $val)) {
$out .= makeList($val['children']);
}
$out .= '</li>';
}
}
return $out;
}
function makeList($a) {
$out = '<ul>';
$out .= makeListItems($a);
$out .= '</ul>';
return $out;
}
?>
<table style="width:100%;background-color: #A5C6DB;">
<tr>
<th class="table_first" style="width:42.5%;">Ledger Name</th>
<th class="table_other" style="width:14.7%;">Opening</th>
<th class="table_other" style="width:14.7%;">Debit</th>
<th class="table_other" style="width:14.7%;">Credit</th>
<th class="table_other" style="width:15%;">Closing</th>
</tr>
</table>
<?
echo "<div id='trial_balance_tree'>";
echo makeList($trial_balance_tree);
echo "</div>";
Now my view look like this and thats exactly i want.
Good evening.
This construction displays the values in a table that sorts them in alphabetical order.Those for example, if you click on the D link, only the names with letter D should be shown, and so on.
PHP code:
<?php
include ('engine/api/api.class.php');
$table = 'dle_post';
$fields = 'xfields';
$where = 'approve=1';
$multirow = 1;
$start = 0;
$limit = 0;
$xfield = 'actor';
$time = '14000';
$tr_new = 0;
$xfields = $dle_api->load_from_cache ($fields, $time, $xfields);
if( !$xfields ) {
$xfields = $dle_api->load_table ($table,$fields,$where,$multirow,$start,$limit);
$dle_api->save_to_cache ( xfields, $xfields);
}
$stack = array();
foreach($xfields as $value){
if($value[xfields]){
$row = xfieldsdataload($value[xfields]);
if($row[$xfield]){
$rowdata = explode( ",", $row[$xfield]);
foreach($rowdata as $value){
if($value){
$value = trim($value);
array_push($stack, $value);
asort($stack);
}
}
}
}
}
$stack = array_count_values($stack);
foreach($stack as $key => $count){
if($tr_new === 0){
echo '<tr class="new">';
}
echo "<td class='blok'>";
echo "<a href=/" . $xfield . "/";
echo $key;
echo " target='_blank' rel='noopener'>";
echo $key;
echo "</a>";
echo "<span>";
echo "(" . $count . ")";
echo "</span>";
echo "</td>";
$tr_new++;
if($tr_new === 1){
echo '</tr>';
$tr_new = 0;
}
}
JQuery:
$(function () {
var _alphabets = $('.alphabet > a');
var _contentRows = $('#countries-table tbody tr');
_alphabets.click(function () {
var _letter = $(this), _text = $(this).text(), _count = 0;
if(_text == 'all') _text = '.';
_alphabets.removeClass("active");
_letter.addClass("active");
_contentRows.hide();
_contentRows.each(function (i) {
var _cellText = $(this).children('td').eq(0).text();
if (RegExp('^' + _text).test(_cellText)) {
_count += 1;
$(this).fadeIn(400);
}
});
});
});
In page:
<div class="alphabet">
<a class="first" href="#">All</a>
A
B
C
...
<a class="last" href="#">Z</a></div>
<div id="conutries">
<table id="countries-table">
<tbody>
{include file="/code.php"}
</tbody>
</table>
</div>
</div>
Everything works fine, but I encounter such a problem - it turns out correctly to output only one value in one line tr ...
When I try to put a 4 td values to the tr line if($tr_new === 4) - they are not sort by alphabetically, they just displayed like this:
Whats wrong? What need to make this code work fine for me?
Thank you in advance for your help!
I made a youtube list where I can click on texts that load youtube videos.
There is only one problem: When I play a video and click on another video link, the video I was playing doesn't stop. So I tried stopping it using jQuery, but no result.
So this is what my php generates:
function generateVideo() {
echo '<script type="text/javascript" src="scripts/video.js"></script>';
$tags = initTags();
$query = '
SELECT * FROM `youtube_links`';
$result = mysql_query($query);
if ( !$result) {
die('Error: '.mysql_error());
}
echo '<div id="content"><table>';
$i = 0;
$className = "";
while ($row = mysql_fetch_array($result)) {
$i++;
if ($i == 1) {
$className = "active";
} else {
$className = "inactive";
}
echo '
<tr>
<td>
<a class="'.$className.'" id="item_'.$i.'" onclick="switchVideo(this)">
'.$row['Title'].'
</a>
</td>
</tr>
';
}
echo '</table></div>';
$query = '
SELECT * FROM `youtube_links`';
$result = mysql_query($query);
if ( !$result) {
die('Error: '.mysql_error());
}
echo '<div id="videoPlayer">';
$i = 0;
$className = "";
while ($row = mysql_fetch_array($result)) {
$link = $row['Link'];
$i++;
if ($i == 1) {
$className = "activePlayer";
} else {
$className = "inactivePlayer";
}
echo '<iframe class="'.$className.'" id="ytplayer'.$i.'" type="text/html" width="640" height="390"
src="'.$link.'?version=3&enablejsapi=1"
frameborder="0">
</iframe>';
}
echo '</div>';
}
And this is my JavaScript:
function switchVideo(obj) {
var idText = obj.id;
var idArray = idText.split("_");
var id = idArray[1];
var videoPlayer = document.getElementById('ytplayer' + id);
var elements = document.getElementsByClassName("activePlayer");
for (var i = 0; i < elements.length; i++) {
elements[i].className = "inactivePlayer";
$(elements[i]).pause();
}
$('.inactivePlayer').each(function() {
$(this).stopVideo();
});
videoPlayer.className = "activePlayer";
}
You can see I added the youtube API to the iframes, so what is going wrong?
It might be a case of async loading of the javascript Youtube API.
Did you checked that?
Greetz, Alex
I have a pretty complex PHP/HTML view. However, I recently changed my site to refresh automatically using AJAX. It currently returns a JSON array, and I need to reproduce my View using that data.
Here is my AJAX:
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters,
});
function updatefilters(ev, ui){
// get the selected filters
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
url: 'updatefilters',
dataType: 'json',
data: { filters: filters },
success: function(data){
var html = "<div id ='board'><table>";
for (i=0 ; i< data.length ; i++)
{
html += "<tr><td>" + data[i].subject + "</td><td>" + data[i].body + "</td></tr>";
}
html += "</table></div>";
$('#board').html(html);
}
});
}
});
Here is my PHP file:
<div id='board'>
<?php
if ($threads)
{
$count = count($threads);
$perpage = 17;
$startlist = 3;
$numpages = ceil($count / $perpage);
if ($page == 'home') {$page = 1;}
$threadstart = ($page * $perpage) - $perpage;
$i = 0;
echo "<table class='board'>
<tr>
<th width='5%'><img src='".base_url()."img/board/icons/category_icon.png' alt='category_icon'/></th>
<th width='5%'>Tag</th>
<th width='50%'>Subject</th>
<th width='7.5%'>Author</th>
<th width='7.5%'>Replies/Views</th>
<th width='15%'>Last Post</th>
</tr>";
foreach ($threads as $list)
{ $i++;
$thread_owner = $this->thread_model->get_owner($list['owner_id']);
$thread_id = $list['thread_id'];
$query = $this->db->query("SELECT f.tag FROM filter_thread AS ft
INNER JOIN filter AS f ON ft.filter_id = f.filter_id
WHERE thread_id = $thread_id");
$result = $query->result_array();
$trunc_body = $this->thread_model->get_reply_summary($thread_id);
$filter = "";
$filter2 ="";
$ent = "entertainment";
foreach ($result as $string)
{
if ($string['tag'] == $ent) {
$filter2 .= "<div id='entertainment'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/entertainment_icon.png' title='Entertainment' alt='Entertainment'/>";
$filter2 .= "</p></div>";
} else {
$filter2 .= "<div id='misc'><p>";
$filter2 .= "<img src='".base_url()."img/board/icons/misc_icon.png' title='Misc' alt='Misc'/>";
$filter2 .= "</p></div>";
$filter .= " [".$string['tag']."]";
}
}
if (!$result) { $filter = "" AND $filter2 =""; }
if ($i > $threadstart AND $i <= $threadstart + $perpage)
{
echo "<tr>";
echo "<td>".$filter2."</td>";
echo "<td>".$filter."</td>";
echo "<td title='".$trunc_body['0']['body']."'>".ucfirst($list['subject'])."<div id='filter'><p></p></div></td>";
echo "<td><p>".$thread_owner."</p></td>";
echo "<td align='right'>Replies: ".$list['replies_num']."<br>Views: ".$list['views']."</td>";
$owner = $this->thread_model->get_owner($list['last_post_id']);
echo "<td>".$owner." <br>".$list['replystamp'] ."</td></tr>";
}
}
echo "</table>";
echo "<br>";
echo "Current Page: $page | ";
echo "Page: ";
for ($n = 1; $n < $numpages+1; $n++)
{
echo "<a href=".base_url()."main/home/$n>$n</a> | ";
}
}
?>
</div>
is there a not too hard way of accomplishing this?
Try adding header("Content-Type: text/plain"); at the TOP of your PHP file.
Also, move the <div id='board'> to a variable inside the script - AFTER the header() function.
Furthermore, change all echo's to variables, put those variables in an array, and use
json_encode($array);
Example:
$output = "<div id='board'>";
$output .= "<table class='board'>
<tr>
<th width='5%'><img src='".base_url()."img/board/icons/category_icon.png' alt='category_icon'/></th>
<th width='5%'>Tag</th>
<th width='50%'>Subject</th>
<th width='7.5%'>Author</th>
<th width='7.5%'>Replies/Views</th>
<th width='15%'>Last Post</th>
</tr>";
echo json_encode( array('output'=>$output) );
So here are my functions,
function getOffset(el){
var _x = 0;
var _y = 0;
while ( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
function makeSeeds(id){
var seedmaker = getOffset(document.getElementById('seedmaker'));
$("#"+id).animate({
"left":seedmaker.left
}, 2000, function(){
$("#"+id).animate({
"top":seedmaker.top
}, 1000, function() {
$(this).hide("explode",{pieces:52},1000);
$("#"+id+"seeds").animate({
"opacity":"toggle",
"top":"+=10px",
"left":"+=30px"
}, 1000);
$("#dialog").html("Successfully created one "+id+" seed!");
$("#dialog").dialog();
$("#"+id+"seeds").hide("slow");
});
});
}
http://dreamsofrenewal.us/jquery.html works just fine, but when I use it on another page with more items, it animates down to the bottom right of the page.
Here's the PHP for that page:
$id = 0;
$c = "<div id='dialog' style='display:none;'></div><table width='95%' class='ti' cellpadding='4' cellspacing='1' style='margin:10px;margin-left:auto;margin-right:auto;'>";
$sql = mysql_query("SELECT * FROM `received` WHERE `uid` = '".$this->uid."'");
while ($row = mysql_fetch_array($sql)) {
$c .= "<tr><td>";
for ($x = 0; $x < $row["amount"]; $x++) {
$i = $id++;
$c .= "<img style='position:absolute;' src='images/crops/" . $this->uI("itembase", $row["thing"], "sprite") . "' border='0' alt='image' id='" . $i . "' onclick='makeSeeds(" . $i . ");' />";
}
$c .= "</td></tr>";
}
$c .= "</table>";
$finalid = $id;
$c .= "<script type='text/javascript'>
$(document).ready(function(){
var ids='";
for ($x = 0; $x < $finalid; $x++){
$c .= "#" . $x . ",";
}
$c .= "';
$(ids).click(function(){makeSeeds(this.id);});
});
</script>";
$sql2 = mysql_query("SELECT * FROM `bought` WHERE `uid` = '".$this->uid."'");
while ($row2 = mysql_fetch_array($sql2)) {
if ($this->uI("itembase",$row2["itemid"],"type") == "crops") {
$c .= "<img src='images/crops/" . $this->uI("itembase", $row["itemid"], "sprite") . "' border='0' alt='image' id='".$row["itemid"]."' />";
}
}
for ($x=0; $x < $finalid; $x++){
$c .= "<img src='images/seeds/turnip.png' id='" . $x . "seeds' style='display:none; position:absolute; left:10px;' border='0' alt='seeds' />";
}
$c .= "<img src='images/makers/seed.png' alt='seedmaker' id='seedmakerx' style='position:absolute; left:10px;' /></div>";
return $c;
If you need more info, I can put up a test page with that PHP for you..
Thanks in advance!
Test with PHP: http://dreamsofrenewal.us/phptest.php
It works fine, it's just duplicating itself? And if you click too many in a row, it lags browser really bad? Any idea how to make it work faster?
//remade this because I said I fixed when I didn't :-X
Well, your browser will lag anyway. If you want to get rid of lag, you have to group animating objects. Exmp.: When at one time user clicks many items, you group them into one DIV(object), and animate object, but not each item. There is actualy no way to animate it smoother over browsers. There is another solution, that you can not move item, but increse size, and then hide it or something like that. Or just make your own animation with less steps.
But the BEST solution is to use canvas, or if you making this game for your own education, make it with WebGL.
Best canvas game, tought