Filtering data in loop Smarty - php

Is there any way to use preg_match or any other similar smarty function to do the following thing:
{foreach $resultsdata as $resultsData}
<div class="site_text">
{$resultsData.text|substr:0:500}
</div>
{/foreach}
I want to filter $resultsData.text and display only one part of this text.

I'm asking because there's a plugin you may use. But it's only for Smarty 3, as I see.
By the way, from your code it seems preg_replace would be a better solution, and it's already internal function - regex_replace - for it.

You are taking idea of templates wrong.
Template should be used only to display data.
But data itself have to be prepared in the business logic part.
Otherwise there will be no good from templates at all.

Related

pulling and outputing php tags from a database

I am trying to create a dynamic FAQ page. I have the following phtml sample :
<div id="faq">
<!-- Start FAQ "Navigation" -->
<div class="faqBox">
<? foreach($this->aFAQ as $k => $val) : ?>
<?= ($val['mQuestion']); ?>
<?= ($val['mAnswer']); ?>
<? endforeach; ?>
</div>
</div>
Which outputs as follows:
For additional payment options - check or money order, please contact us at iBrandingLevel == 2 ? $this->oStore->getSuppPhone()." Monday to Friday ".$this->oStore->getSuppHoursOpen()." - ".$this->oStore->getSuppHoursClose()." ".$this->oStore->getSuppTimeZone() : "(888) 455-3237 x2 from Monday to Friday 8:00am - 4:30pm MST/Arizona."; ?>
The above text is just the first $val['mAnswer'] (I didnt include the question as that is working properly).
The html is being rendered however obvoiusly the php isn't. the <? and ?> are being removed and just code is displaying. Is there a fix for this? or is my approach fundamentally wrong.
thanks
Your approach is fundamentally wrong, you are outputting PHP code as if it was HTML text and try to execute it.
It is possible to execute code from a string, you can look at the Eval method (http://php.net/manual/fr/function.eval.php) in PHP, but it is not recommended to do this. There are better ways to resolve your specific issues than to output PHP code directly.
What you could do is send a few variables to the view, and use if conditions there.
You could also prepare the full string you need before the view and then all that would be needed is to display it.
To elaborate a little about Eval :
1- If the code you execute within the Eval comes from a user, it is extremely dangerous.
2- If not, there is very often a better solution to the problem, using Eval makes it harder to debug.
Actually, I'm not sure I should answer this.
First, the answer to your request is the mixed eval ( string $code ) php function.
Second, FORGET IT. IMHO, this could be one of the most dangerous things you could think in.
Thanks everybody for the input and resulting discourse. The php code that was being stored in the database was not being input by users, it was all completely internal, however it still shouldn't be there.
I ultimately went through the database and set a %%variablename%% in place of the php code and then upon retrieval I wrote a script that would:
preg_replace("/\%\%variablename\%\%/", $desiredPhpcode, dbRetrievedString).
all instances of %%variablename%%.
It seemed the safer and more sound approach. I don't know if this is an IDEAL approach that anybody else could benefit from if caught in this circumstance or if it 'just works', but I thought I would share.
Thanks Again for the input it helped enormously
PHP is server-side language. Outputting it to client does not make any sense, as there is no one to interpret it.

Php - replace question mark sign

Is it possible to replace php tags to something custom?
Smarty library can assign values and then render them so instead of:
<?php echo $name; ?>
you can just assign value in business logic and then in template just say
{name}
I'd like to make my own function/class/library so when I write { in index.tpl, browser will think its < ?php echo ..
Can somebody point me somewhere?
replace {variable} with regexps and then eval-it
here is simple template engine, very similar to your idea
i mean, better is use existing templates engines, like Latte, Twig or Smarty. Its not necessary reinventing wheel :)

Is this html code using php inside it without the <?php ?> signs?

{$smarty.section.page.index}
{/if}
{/section}
{if $pagesArray.is_next_page eq 'Y'}
<span class="resultsnext">
>
</span>
{/if}
I have written simple php based websites before but this is the first time I am getting involved in a complex php website that another person has already finished to a large extent. This is also the first time I'm seeing this type of code in a html template section of the website.
Basically, what I'm curious is, what are all the code in the {} curly brackets? Is it some sort of php code? Another php file refers this .html file that is containing the above code.
There is a lot of content being dynamically generated, but I've never seen '{}' curly brackets being used in a .html file while having it being used as part of a template so I was wondering if some of you guys could enlighten me.
thanks.
That is a PHP templating language, specifically, Smarty.
Smarty parses the file for its own syntax and replaces their placeholders with variables, etc that are bound to the smarty view.
Smarty Documentation.
That's smarty:
http://www.smarty.net/
You're looking at Smarty tags. Here's a link to the current documentation.
It's smarty :)
Actually you're looking at sections.
http://www.smarty.net/docsv2/en/language.function.section.tpl

Should one use PHP to print all of a page's HTML?

So I've always developed PHP pages like this: <?php goes at the top, ?> goes at the bottom, and all the HTML gets either print()ed or echo()ed out. Is that slower than having non-dynamic html outputted outside of <?php ?> tags? I can't seem to find any info about this.
Thanks!
--Mala
UPDATE: the consesus seems to be on doing it my old way being hard to read. This is not the case if you break your strings up line by line as in:
print("\n".
"first line goes here\n".
"second line goes here\n".
"third line");
etc. It actually makes it a lot easier to read than having html outside of php structures, as this way everything is properly indented. That being said, it involves a lot of string concatenation.
I'm not sure about speed, but it's typically best practice to separate dynamic elements and the display of them.
Check out a framework like CodeIgniter: This has a "controller" and a "model" that grab data, sort it or do whatever you like with it, and then feed it to a "view" (some sort of template).
This paradigm is called MVC, and is a really, really valuable thing to learn about. I've found its chief advantage to be easier-to-maintain code. I don't end up with a monster document that I have to re-learn each time I approach it.
Resources:
CodeIgniter
MVC
The difference in speed is probably negligible, however, when **print()**ing out all of your HTML with PHP, the code can get very ugly, and makes it much harder to read than if you just have plain HTML.
Edit: Also, if you're are **print()**ing out static HTML that doesn't change, really what is the point? It gives you no added benefit.
Pros
None that I can see
Cons
Code that is hard to read
One more step in processing for the PHP engine, which although probably not noticeable, it is an extra step.
The speed is negligible - trust me, this will not be your bottleneck.
Along with any other MVC framework, you might want to check out a simple templating system, such as Smarty, which separates your PHP logic from your HTML and also does caching.
I don't know if it's slower or faster, but (in my opinion) it makes the code a lot more difficult to understand. Which I guess is why I don't typically do it.
It is almost the same from a performance point of view.
I would set the focus on the readability of the code. If you have a performance problem, figure out the bottleneck and cache it.
Is that slower than having non-dynamic html outputted outside of <?php ?> tags?
Well yes, it is... marginally. But that's not really the issue: it's all about the readability.
this way everything is properly indented
Your example isn't indented at all, which is fairly typical for the print-heavy, PHP I've unfortunately had to maintain!
Try this approach to keeping good, consistent indentation:
<ul>
<?php
// block of arbitrary code blah blah
//
$conditions= get_conditions_from_request();
$isadmin= $user->privileges>=PRIV_ADMIN;
?>
<?php foreach (select_things($conditions) as $thing) { ?>
<li>
<strong><?php h($thing->title); ?></strong>
<?php if ($isadmin) { ?>
<a href="/editthing.php?id=<?php u($thing->id); ?> (Edit) </a>
<?php } ?>
<?php h($thing->description); ?>
</li>
<?php } ?>
</ul>
(This presumes a function h that calls echo htmlspecialchars and u that does echo htmlspecialchars urlencode. Getting this escaping stuff right is essential to having a secure site, and is something that's almost always wrong in print-based PHP, as it tends to use "blah $var blah"-style templating without any escaping at all.)
Maybe not the best practice, but I choose to mix and match print() statements. For large chunks of layout code, I don't use print(), but if I'm rendering a complex if/else or for/while block and I'd be exiting the PHP block every other word, then I'll print out the non-dynamic text with the dynamic text.
Performance is very negligible at best. You can create a page, and put a timer on it. (Here is a tutorial on creating a script timer)
Output the exact same data both ways, and measure it with as many samplings as you can get, this should roughly tell you which is faster. I'm guessing very close to the same.
I have seen a lot of these pages with PHP embedded inside HTML, and I don't like it. As Alex Mcp suggested you should be thinking about a MVC model.
The problem with scripts embedded into html is the flow control and logic aren't easy to read, and there are some wierd problems that occur here and there. The best solution for me is usually to use Smarty or the Zend Framework to create template pages and then swap the data that goes in and out. Much easier to manage in the long run.

PHPTAL and nested templates. Possible?

I've been playing around with PHPTAL for the last couple of days. Overall I really like it. It's been much easier to get into than most others I've looked into. I am having one particular problem, though.
Here's the issue. I am trying to nest two templates. Let's say InnerClass has this template:
<div>Hello World!</div>
OuterClass has the following template:
<div tal:content="myVar">This text should be replaced with the HTML above.</div>
InnerClass also has a method called render(), which essentially calls themplate's execute() method and returns the content. So I do this in the outer class:
$template->myVar = $innerClassObject->render();
I, then, display the content of the OuterClass. The problem is that the rendered HTML of the inner class comes escaped and I see ">" and "<" instead of actual tags. It seems that myVar is completely escaped before its content is displayed.
Since this approach does not work, what is the best way to nest PHPTAL templates? I assume it's possible and it's just lack of knowledge on my end, so any input is appreciated.
If you want to insert arbitrary markup in a template, then use structure keyword:
<div tal:content="structure variable_that_contains_html"/>
but if you want to embed one PHPTAL template in another, then use macros:
macros.xhtml:
<div metal:define-macro="greeting">Hello World!</div>
page.xhtml:
<body><tal:block metal:use-macro="macros.xhtml/greeting"/></body>

Categories