Twig template extract a subset - php

Is is possibile to extract a piece of a twig template?
I need to manage a table ajax refresh, I have a twig template for example:
<html>
<body>
<table>
<thead>
<tr><th></th></tr>
</thead>
<tbody id="mypiece">
<tr><th></th></tr>
<tr><th></th></tr>
</tbody>
</table>
</body>
</html>
In the first load I need the whole template, via ajax I need just the #mypiece content, is it possibile to extract it from twig using the DOM id or with some other markers?
The only solution I found is to divide this in two different template and use an include steatment.
whole.html
<html>
<body>
<table>
<thead>
<tr><th></th></tr>
</thead>
<tbody id="mypiece">
{% include 'content.html' %}
</tbody>
</table>
</body>
</html>
content.html
<tr><th></th></tr>
<tr><th></th></tr>
But I think this is really a bad solution...

Well, I personally prefer do actually divide them, but if you intend to get something with AJAX as well - try using embeded controllers (in this case, specifically for your XHR request), for example:
<tbody id="mypiece">
{{ render(controller(
'SomeBundle:SomeController:someAction',
{ 'someParameter': "something" }
)) }}
</tbody>
This is a lot better then to parse some rendered template to get part of it, because to me it seems like design flow.
Even better solution is to return specified json data on ajax call and render it in one of the javascript template engines on the client side.
Hope this helps, cheers.

Related

Why the result of laravel eloquent incrementing always?

I try to execute select * from articles where category_id=1 in laravel eloquent model as below.
$articles = Article::where('category_id', '=', $id)->get();
And i pass this to my view file by using compact method as below.
return view('homeview.index', compact('articles'));
And i use this $articles variable in foreach loop and print each article's title in view file. But the thing is when i try to execute this, my view file is refreshing continuously and incrementing the same div class which i used to print the article titles. I tried to use above code as raw query also. It also generates the same issue.
below is my view file.
<tbody>
#foreach($articles as $article)
<tr>
<td><img src="{{asset('/img_thumbs/'.$article->img_thumb)}}"></td>
<td class="-align-center">
<h4>{{$article->title}}</h4>
<p>{{$article->sub_paragraph}}</p>
</td>
<tr>
#endforeach
</tbody>
Please help me to solve this.
The bottom line is, THere's an error in your HTML.
You are opening <tr> but not closing it.
<tbody>
#foreach($articles as $article)
<tr>
<td><img src="{{asset('/img_thumbs/'.$article->img_thumb)}}"></td>
<td class="-align-center">
<h4>{{$article->title}}</h4>
<p>{{$article->sub_paragraph}}</p>
</td>
</tr> <!-- HERE -->
#endforeach
</tbody>
i used some java scripts for my application. That repeating thing happening because one script file. After i comment it, my page is working fine. I used some template called inspinia and it is happening because inspinia.js file.

Problems with Bootstrap tables in PHP

So, I found this cool PHP script on the web called Listr. It makes your Index directories much prettier. I also noticed someone made a version specifically for Bootstrap, but opted not to use it (I don't want something over complicated, nor do I want to compile things).
So, I went along with the original Listr, added and removed a couple things to make it mobile friendly, and here is the result:
So, for whatever reason, only the first line shows up properly under Name. I really don't know why; I've tried several placements of <table>, <th>, and <tr>... none of my methods seem to work.
Here is my code: http://pastebin.com/uHSJhFyq (sorry, it's minified! you'll have to unminify it to read it :/)
Try this for the <tbody>:
<tbody>
<?if($folder_list):?>
<?foreach($folder_list as $item):?>
<tr>
<th><a href=<?=$item['name']?>/><?=$item['name']?></a></th>
<th><?=$item['size']['num']?><?=$item['size']['str']?></th>
<th><?=time_ago($item['mtime'])?> ago</th>
</tr>
<?endforeach;?>
<?endif;?>
<?if($file_list):?>
<?foreach($file_list as $item):?>
<tr>
<th><a href=<?=$item['name']?>.<?=$item['ext']?>><?=$item['name']?>.<?=$item['ext']?></a></th>
<th><?=$item['size']['num']?><?=$item['size']['str']?></th>
<th><?=time_ago($item['mtime'])?> ago</th>
</tr>
<?endforeach;?>
<?endif;?>
</tbody>

PHP Functions to display sections around the site?

I need some help. I am working on a backend of a website and I want to create functions where I can re-use the same code instead of duplicating it.
So I will have certain "sections" that contain information, such as:
getQuickInfo
function getQuickInfo() {
echo '
<div class="portlet">
<div class="portlet-header">
<h4>Quick Info</h4>
</div>
<div class="portlet-content">
<table cellspacing="0" class="info_table">
<tbody>
<tr>
<td class="value">'.getCount("total_users").'</td>
<td class="full">Total Users</td>
</tr>
<tr>
<td class="value">'.getCount("count_open_requests").'</td>
<td class="full">Open Support Requests</td>
</tr>
</tbody>
</table>
</div>
</div>
';
}
Now I know I am approaching this the wrong way, that's why I am posting this question. But that is just an example of a Quck Info section I would like to re-use on other pages, so I can sitck it wherever I want and just do getQuickInfo()
For this example, that function works fine. I would like suggestions on a better way to do it, and also for some other sections it won't be that easy it will have some Mysql queries and grabbing information from a database, which I can't store that within an echo.
How does everyone else accomplish stuff like this?
My main goal is to be able to output sections wherever I would like:
getQuickInfo()
getAdminNotes()
getSupportRequests()
etc.
Thanks!
Much as I am loathed to mix raw HTML with PHP code in templates, I know others disagree with me and this is one place where it might be a valid use.
So you would create a file that looks like this:
quickinfo.php
<div class="portlet">
<div class="portlet-header">
<h4>Quick Info</h4>
</div>
<div class="portlet-content">
<table cellspacing="0" class="info_table">
<tbody>
<tr>
<td class="value"><?php echo getCount("total_users"); ?></td>
<td class="full">Total Users</td>
</tr>
<tr>
<td class="value"><?php echo getCount("count_open_requests"); ?></td>
<td class="full">Open Support Requests</td>
</tr>
</tbody>
</table>
</div>
</div>
...and in you main page, you can just do:
include('quickinfo.php');
You can easily adapt this to use the result of queries. You would simply perform the query in the main page, and assign the results to a named variable. Then in the template page you use the data in the named variable to generate the page. This means that you can use the same code to generate different results based on different queries - as long as the result are held in the same named variable.
If you're using php 5 you should considered using PHP's object orientation support.
http://php.net/manual/en/language.oop5.php
This way you can create a class which has methods that print out stuff and hold values and then instantiate this class and call it's methods as needed.
I'm no php guru, but maybe you should create separate .php files for each of those sections (something like quickinfo.php, adminnotes.php, etc) put your html layout inside, and maybe even the php functions you need (or you could put them in a separate file, this depends on whether the logic you need is too complex, if it's fairly simple you can put everything in the same file)
Then you would do something like include('quickinfo.php') wherever you want to use those sections.

Terrible Layout - php and html/tables intermxed

I am working on a project currently where the Index.php file basically acts as a layout page and basically uses tables for the layout.
Please have a look at it's contents below. This is just a small part of the code, there's much more like this.
I need to pass on this file to a Front End Developer/ Designer so that he could change the layout as well as change the code to use CSS instead of Tables for the layout. But I think this is a mess and the designer might have issues understanding and modifying this.
What's the best way to structure and organize this code so that
1)The code becomes much more cleaner, structured and organized.
2)It's easier for the Designer to understand and change the layout.
<table width="770" border="0" cellspacing="0" cellpadding="0" align="center">
<tr><td colspan="3"><?php include("header.inc.php"); ?>
</td></tr>
<tr>
<?php
if ($xview == "main" || $show_sidebar_always)
{
?>
<td width="185" id="sidebar_left" valign="top">
<table width="90%" class="buttons" cellpadding="0" align="center">
<tr>
<td>
<!-- Begin Version 5.0 -->
<?php echo $lang['HOME_LINK']; ?>
<!-- End Version 5.0 -->
</td>
</tr>
<tr>
<td>
<?php echo $lang['POST_LINK']; ?>
</td>
</tr>
<?php if($enable_calendar) { ?>
<tr>
<td>
<?php echo $lang['POST_EVENT_LINK']; ?>
</td>
</tr>
<?php } ?>
<?php if($enable_images) { ?>
<tr>
<td>
<?php echo $lang['POST_IMG_LINK']; ?>
</td>
</tr>
<?php } ?>
<?php if($forum_dir) { ?>
<tr>
<td>
<?php echo $lang['FORUM_LINK']; ?>
</td>
</tr>
<?php } ?>
<tr>
<td>
<?php if($auth->id) { ?>
My Account
Watch List
Logout
<?php }else{ ?>
Login
Sign up
<?php } ?>
</td>
</tr>
</table>
<br>
To improve readability try using Alternative PHP Syntax in your HTML output.
<?php if($enable_calendar): ?>
...
...
<?php endif; ?>
Instead of:
<?php if($enable_calendar) { ?>
...
...
<?php } ?>
The closing blocks are a bit more intuitive than just a closing curly brace.
It would be better to let the designer create a completely new layout and then add the PHP logic into into. If you rewrite this I strongly suggest using a template engine.
Mmm. Here are some advices:
1) Use tables only when you want to show a table. Really. Almost 95% of the cases can and must be done using divs.
2) Use a template engine! so you don't mess up your html with your php code (and the designer won't break it). Good templating engines are Smarty (the most popular) and TemplatePower
Hope this helps. Cheers
I recommend you use a Template Engine, like the Smarty Template Engine
You can easily implement.
Use a templating engine like Smarty. Now if you ask around, most people hate Smarty for some reason or another, so do your research first. However it's great when you want the CSS / HTML to be in one place, and the business logic somewhere else.
Regardless of what you end up using, do a little research into the MVC design pattern -- that's a much cleaner way in general of keeping things organized.
I would first start by sorting out all the indentation, I know that's a corny thing to say, but it will be 10 times more readable than it was before you start optimising it.
<table>
<tr>
<td><?php echo "hi"; ?></td>
<td>cell 2</td>
</tr>
</table>
if you are going to intersperse <?php if(true == true) { ?> with <?php } ?> then try to make sure that they line up.
As a general rule on layout though, tables within tables is soooo 90s :P try reading up on CSS positioning using div elements and laying them out using the CSS instead of in the HTML.
I would take the time to invest your time to a CMS such as WordPress or Drupal, and learn how to apply CSS and PHP styles to the CMS. In particular, as I am familiar with WordPress, I can confidently state that developing a theme for WordPress allows you to intermingle direct PHP.
If using a CMS is not an option, then you probably should decide to create an API for your functions, create proper documentation for these API functions, and ask your developer to call off the API, for another layer of abstraction.
I do not recommend using a templating system such as Smarty, as it creates another layer of difficulty for your developers to learn. PHP as it stands is perfectly fine.

Any problem with using includes for everything but page-specific content?

I'm developing a site that's pretty lightweight on the interface and mostly database driven (equal amounts read and write). It's written in PHP and I've found the easiest way to make each page is:
Page:
<?php include("header-nav.php"); ?>
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Data Point 1</td>
<td>Data Point 2</td>
</tr>
<tr>
<td>Data Point 3</td>
<td>Data Point 4</td>
</tr>
</table>
<?php include("footer.php"); ?>
header-nav.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Welcome</title>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
</head>
<?php include("db_connect.php"); ?>
<body>
<div id="wrapper">
<h1>Welcome</h1>
<ul id="nav">
<li>Home</li>
<li>Data</li>
</ul>
footer.php:
</div>
</body>
<?php mysql_close($dbc); ?>
</html>
All of these pages by themselves are not valid and may produce errors. Working together to create a whole page, they look great.
My question is: Would this be an efficient and easy to maintain solution?
It seems that just adding a couple includes (one at the top and one at the bottom) makes sense. Especially because the site is so lightweight that I don't need a web framework. It just feels uncomfortable to create pages without starting with <html><head>...etc.
This is definitely an okay thing. I would highly recommend it. This way if you need to change the header or anything you can do so in once place easily. And the read time for hitting the file system for the include really isn't that big of a concern. So I would say that this is definitely acceptable.
"All of these pages by themselves are not valid" - I'm not sure what you mean by this. You mean a HTML Validator wouldn't pass them? Well of course not - they are fragments of pages. What matters is what the validator says when ran against the HTML the executed PHP generates.
This is one approach, and depending on the size of the problem you're tackling it's a valid one.
Yes, IMO this is a perfectly good way to do things, especially for a small site. Done it myself many times.
Get over your discomfort. Most IDEs (Dreamweaver comes to mind) actually support this way of developing sites, and will display content correctly and honor the includes if you prefer a WYSIWYG.
I develop sites using includes, like so:
site-header.inc:
require_once 'html-header.inc';
<div id="header">
/* menus, navigation, etc. */
</div>
<div class="content">
site-footer.inc:
</div>
<div id="header">
/* menus, navigation, etc. */
</div>
require_once 'html-footer.inc';
Where "html-header.inc" and "html-footer.inc" are your HTML header and footer tags and elements (title, meta, etc.). I then have functions to allow me to add CSS, JavaScript, titles, anywhere on the page, and use ob_start() and ob_end_flush() to handle these in the footer, actually. e.g.
stylesheet_register($path, $media="screen", $type="text/css");
javascript_register($path, $type="text/javascript");
title_set($title, $overwrite=true);
It your basic concept of abstraction: Don't write the same "header" and "footer" HTML code twice. Same applies to any PHP functionality which can be easily abstracted away and decoupled. Best of luck.

Categories