Converting spaghetti code to Twig - symfony

Need to convert script with "spaghetti code" to Twig. Read Twig documentation and got basics working. However, I need advice on how to do everything properly, so no re-conversion is needed later. Let's say current script looks following:
file index.php:
<?php
$page_message="do it";
function display_dropdown($max)
{
for ($i=0; $i<$max; $i++)
{
echo "<option value='$i'>Option $i</option>";
}
}
?>
<!DOCTYPE html>
<html>
<body>
<h1><?php echo $page_message; ?></h1>
<form method="post" action="<?php echo basename($_SERVER["SCRIPT_FILENAME"]); ?>">
<select name="whatever"><?php display_dropdown(10); ?></select>
<input type="submit" value="go">
<?php include("footer.php");?>
</body>
</html>
footer.php looks:
<?php
$footer_text="blah blah";
?>
<footer><?php echo $footer_text; ?></footer>
As far I understand, my index.php should look like this when converted to Twig:
<?php
$page_message="do it";
function display_dropdown($max)
{
for ($i=0; $i<$max; $i++)
{
echo "<option value='$i'>Option $i</option>";
}
}
$twig_params_array=array("page_message"=>$page_message, "footer_text"=>"blah blah");
require_once("../lib/Twig/Autoloader.php");
Twig_Autoloader::register();
$loader=new Twig_Loader_Filesystem("templates");
$twig=new Twig_Environment($loader);
echo $twig->render("index_template.html", $twig_params_array);
?>
Then I should create index_template.html and footer_template.html (or whatever) with following code:
index_template.html
<!DOCTYPE html>
<html>
<body>
<h1>{{ page_message }}</h1>
<form method="post" action="{{ _self }}>">
<select name="whatever"><?php display_dropdown(10); ?></select>
<input type="submit" value="go">
{{ include('footer_template.html') }}
</body>
</html>
footer_template.html
<footer>{{ footer_text }}</footer>
If I understand right, it's also possible to "include" functions in Twig templates (with some tweaking in templates), so I don't need to rewrite existing PHP functions like display_dropdown(). Because dropdown is not displayed at the moment...
The thing that concerns me is array with variables (passed to Twig render function). Do I miss something, or is it really needed to manually define each variable (like $page_message and $footer_text) before Twig can work?
It seems like a lot of work to do, because in "spaghetti code" if I define variable somewhere, I can access it at any time just by using echo function. Now, it looks I need to view every single variable that exists in PHP code and manually pass it to Twig parameters array. Really?

Since no solution was provided, I found it myself. All you have to do is use such a line of code, so all the variables you have in your PHP file (counting included files) become available in Twig templates, and you don't need to re-write anything when new variables are added to PHP file later (they also automatically become available in Twig):
echo $twig->render("template_file_name.extension", get_defined_vars());

Mindaugas, just changing the technology you use to render views is not going to make the code less tangled.
I think you should go one step further and divide responsibilities, by using an MVC framework, like Symfony, which uses Twig as its default templating language.
Good luck!

Related

How to design a php page theme template in wordpress using either html or css?

<?php
/*
Template Name: isbn
*/
?>
<form action="" method="post" name="myForm">
Filter <input id="isbn" type="text" name="isbn" />
<input type="submit" name="submit" value="Submit" /></form>
<?php get_header(); ?>
<?php
if(isset($_POST['submit']))
{
global $wpdb;
$table_name = "isbn"; // change this to your table name
$field = $_POST['isbn']; // change this to your isbn field $_POST['ISBN'];
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name where isbn = '".$field."'");
foreach ($retrieve_data as $retrieved_data) {
echo $retrieved_data->title;
// echo $retrieved_data->image; // for image
}
}
?>
This is a search form which i want to design. I have created this form in a page template named isbn. But when i am opening that page for editing i am unable to do this. I am using divi theme in wordpress.
So divi theme is not allowing me to edit this page. Due to which this page is looking very bad in look wise.
Can anyone help me for designing this page by giving their codes or simply by giving their suggestions?
I am facing one more problem whenever i am writing css code in above code i am not getting anything. So i am totally blank that how to deal with this
Just create a WordPress page and add shortcode which you added in functions.php before. Don't create template for this page just use your shortcode only.
First, you have to create a page using divi theme, then create shortcode for this form in functions.php and then use this shortcode in your page.
you are inserting the form above the get_header(); function, so it will be outside of the html tag and outside of the body tag. Move it into the body, then it should at least appear on the page, and you'll see what you need to do next.

Files included in wordpress header.php are not accessible of page templates even after calling get_header()

I am developing a custom wordpress template. I have a few page templates for the layout.I call get_header() and get_footer() at the top and bottom of my page templates respectively.
Now the issues is. I have used two or three require_once() in the header.php file to include php class file. And in one of the included file , I have created an object for the included class files. But when I call those objects in my pages files (-- where I used get_header()--) it says undefined variable.
This is my wordpress header.php
// THIS IS MY header.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if(session_id() == '')
session_start();
date_default_timezone_set('Asia/Dubai');
require_once('risk-profiler/configuration.php'); // Config file
require_once('risk-profiler/dal.php'); // One class files
require_once('risk-profiler/bl.php'); // another class file
require_once('risk-profiler/form_handler.php'); // Were Objects for the classes are created
?>
form_handler.php
if (!isset($data))
$data = new DataAccessLayer(sql_server, sql_user, sql_password, sql_database);
if (!isset($bl))
$bl = new businessLogic;
$data is my object for the database class and $bl is an object of another class.
Now this is where I call get_header() risk_profile_questionnaire.php and I included two form (risk-profile-select-profiling-country.php & another.php) in this file(form) is where I call that object and it is not accessible.
risk_profile_questionnaire.php is as
<div class="form-group">
<label for="" class="col-md-4 control-label">Country : </label>
<div class="col-sm-8">
<select class="form-control input-lg" name="version_details">
<?php
$version_details = $data->get_version_list();
while ($row = mysqli_fetch_array($version_details)) {
echo"<option value='" . $row['country_code'] . "|" . $row['version'] . "'>" . $row['country_name'] . "</option>";
}
?>
</select>
</div>
</div>
Can anyone helpme on why my objects are not accessible at that point.
I can't test now, but my guess is that this is because of variables scope.
If you are going to use a global variable inside a function in PHP, you need to declare it as global at the beginning of the function.
Since you are including header.php (and the rest of files included from header.php) from the function "get_header", variables are limited by default to the scope of "get_header" function.
Try to declare the global variables you need to use at the beginning of header.php file, for example:
global $data;
Variables scopes in PHP: http://php.net/manual/en/language.variables.scope.php

Disable WordPress from adding <p> tags

All I've got is the following little snippet of code:
<select size="1" name="EventHour<?php echo $i; ?>">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
: <!-- note this character -->
<select size="1" name="EventMinute<?php echo $i; ?>">
<option>00</option>
<option>05</option>
<option>10</option>
<option>15</option>
<option>20</option>
<option>25</option>
<option>30</option>
<option>35</option>
<option>40</option>
<option>45</option>
<option>50</option>
<option>55</option>
</select>
The should output fine. However, WordPress adds a p-tag around both of my select-elements as well as around the ":"-character. This makes them all end up on different rows.
I've installed and activated the WordPress plugin "Disable Visual Editor WYSIWYG" on this page without any success. Any other ideas what I can do to stop this from happening?
Use this:
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
in your functions.php
Here's the complete answer: http://codex.wordpress.org/Function_Reference/wpautop#Disabling_the_filter
Wordpress modifies and cleans your entered HTML both in the editor and at output.
Use this plugin to get unmodified markup into your posts:
https://wordpress.org/extend/plugins/raw-html/
Try this in your functions.php
<?php remove_filter ('the_content', 'wpautop'); ?>
<!-- wp:html -->
You can insert your code between these tags.
<!-- /wp:html -->
Tested on 5.6.2 WordPress
You can minify your code. Wordpress won't destroy code if everything is on one line.
I do that when I want to put <style> or <script> tags inside certain posts.
In my case, I'm doing it manually for the page:
Result that shows extra p tags:
<p><?php if($description){ echo $description; } ?></p>
<p><?php if($description){ echo wpautop($description); } ?></p>
Result that removes extra p tags:
<?php if($description){ echo wpautop($description); } ?>
Note, I removed the p tags around the echo, then added wpautop to the echo.
End Result:
<p>description content</p>
If the post is custom post type, you can add meta box with add_meta_box and there you can initialize your own editor with wp_editor which can be customized. For example you can pass settings to the tinymce like 'force_p_newslines' and 'forced_root_block'
At least with contact-form-7 I had some success using a html-minifier to prevent those pesky p-tags. Came here because I googled if others also find this as frustrating as I do.
If you still have problem after code minifire then use just convert your tag to div where p tag is automatically add.
if anybody else is having this problem and can't or doesn't want to install another plugin, or again can't or doesn't want to have to edit their functions.php file, you can also do this!
My original code:
your original code
that worked wonderfully..
and then wordpress happened
My code with the workaround:
your original code
//
that worked wonderfully..
//
and then wordpress happened
So long as I make sure to not have any empty lines in my code this seems to be a workaround for me at least. I'm wondering if the : wasn't enough to trick it not to add a p tag, but I'm coding in javascript and it worked for me.
Another workaround:
Put your select inside a <div> tag, without any whitespace chars between them. So Instead of :
<select ...>
</select>
<select ...>
</select>
You write this:
<div><select ...>
</select></div>
<div><select ...>
</select></div>
I've had the same problem with <a> elements, and this solved for me.

Aptana 3 format phtml files

i've been using aptana for a while now, and i have a little question because it is driving me mad. It is possible to recode formmat rules if there is no option in the preferences options (Windows->Preferences->Aptana studio->Formmatter).
I want to recode format rules of .phtml files for a simple rule, <?php ... ?> tag. Everytime i autoformat .phtml files, the "tag" ?> adds a line. I do not want that new line, i want it keep at the same line as the initial tag.
if i write in a .phtml file something like this:
<?php if ($this->x > 10) : ?>
<p> It is not greater than 10 </p>
<?php else : ?>
<p> It is greater than 10 </p>
<?php endif : ?>
and do autoformat, the autoformat return this:
<?php if ($this->x > 10) :
?>
<p> It is not greater than 10 </p>
<?php else :
?>
<p> It is greater than 10 </p>
<?php endif :
?>
I hope you can understand my question. How can anybody recode a format rule or show me the option where i can say do not add a new line in ?> tag.
Thanks in advance.
P.D.
Excuse if i have some grammars errors, if been a while since i have to write in english.
It's not possible (yet) with the current formatter capabilities. However, I've created an issue for that at http://jira.appcelerator.org/browse/APSTUD-3340 and you are more than welcome to add yourself as a watcher, so you will get notified.
That main problem is that the current formatter works partition-by-partition, and not by looking at the entire content as a whole.
Cheers

Wordpress if else requirements for comments

I am not sure where to start, but I want to add in a symbol or change the css for the comments for registered users. Show a difference between non registered user comments and registered user comments.
How would I go about adding this to my wordpress website?
<div class="commentdetails">
<p class="commentauthor"><?php comment_author_link() ?></p>
<?php if ($comment->comment_approved == '0') : ?>
<em>Your review is pending approval by gsprating staff.</em>
<?php endif; ?>
<p class="commentdate"><?php comment_date('F jS, Y') ?>
IP/Hostname: <small>(coming soon)</small>
<?php edit_comment_link('Edit Comment','',''); ?>
</p>
I want to add make it so that the entire class is a different color if the user is a registered logged in user.
Here's an all php version of Saladin's code using the standard if/else sysntax:
<?php
if ($comment->user_ID) {
echo "<div class='comment_registeredUser'>";
}
else { // The user is not logged in
echo "<div class='commentdetails'>";
}
?>
Putting all the code in php has fixed execution errors for me. Of course, that may have been because I was doing something else wrong.
As comments are displayed in the wp_list_comments() function, you will need to edit the code there. The easiest way to achieve this is to use a simple if/else statement checking whether or not the comment has a user ID associated with it. If it does, that means the comment was made by a registered user.
Of course, as well as this, you will need to create a new CSS class to give the distinction. Here is some example code:
<?php if($comment->user_ID) : ?>
<div class="comment_registeredUser"> <!-- Or whatever you decide to call the CSS class -->
<?php else : ?> <!-- The commenter isn't a registered user -->
<div class="commentdetails">
<?php endif; ?>
// Then include the rest of the code as is
The $comment->user_ID variable will return a true if the comment poster is a registered user and was logged in when they posted the comment. The code above will assign your custom CSS class to the div if it does indeed return true. If not, it will simply apply the standard class and styling.
There is also a really good tutorial for developing themes over at the Wordpress Codex. Definitely worth having a read through if you are unsure on what you need to do to create/edit your WordPress theme.
Edit: Cleaned up the answer and better explained the correct logic.

Resources