I am using php framework laravel and I would like to implement shortcodes.
Does anyone have a suggestion how to go about implementing shortcodes that could be inserted by user into a page or blog post.
Example, lets say I would like to have a shortcode for gallery that has some images, something like
[gallery=id]
which would then display that particular gallery. Ofcourse I have gallery model and gallery & images tables.
My first thought is that I would have to scan the content of the page/post and look for shortcode and when I find a particular shortcode, then what? What do I insert instead of it?
I can't insert php code that loops through the gallery and produces output. I guess the best way to do it would be to run a function that returns complete html code that I insert instead of the shortcode.
Is it possible to return a view from a function and insert the result into a page/post?
Depending on what kind of "shortcode" you want, there are numerous options here:
Blade Directives
Blade Layouts
Blade Sub-Views
Blade Stacks
To be clear, I'm assuming you want to insert this into content blocks stored in a db or something, not in your exiting view files.
Assuming you want inject the text into your view for display, you could allow content creators to use a templating format like mustache (https://en.wikipedia.org/wiki/Mustache_%28template_system%29) with server side callbacks/helpers/partials (in the view) to populate your own custom tags with dynamic content (gallery links in this case).
Main Points
I'd stick to a basic well known templating format like
mustache for this. In laravel, allow to Blade templating notation, it sounds like you want for this case to register a Blade::directive: https://www.laravel.com/docs/5.3/blade#service-injection.
I'd try to use an existing library if one such exists before
attempting to create your own short-tagging markup parsing /
callback paradigm. Blade has functions and methods handle such callbacks.
#2 is not necessary, but highly recommended, but #1 should be considered near religious.
UPDATE: as point out in other answers, Laravels built-in templating Blade, has this functionality, so stick to it's format and functionality.
Here's my suggestion (in pseudo-laravel/php):
Assume your marked up content from model pulled into the controller is in $content['blade_markedup_content' => 'here is my new gallery: #gallery(1)'] to be passed to the view.
Add a Blade directive #preprocess() to and in the template/view use <p>#preprocess($blade_markedup_content)</p> in place of just substituting raw <p>{{$blade_markedup_content}}</p>.
In the respective callback function for the #preprocess() directive
Instantiate a new $my_compiler = new BladeCompiler();
Register to this new blade compiler directives to handle the like #gallery(1) you put in your blade_markedup_content
return from the #preprocess() with $my_compiler->compileString($blade_markedup_content);
Viola... In theory, this should result in a parsed and substitute string from #preprocess($blade_markedup_content) in the original template.
I'm creating a website with CakePHP; the problem now is that I want to show in the website footer (that will be visible on all the pages), the result of a query (e.g. "Most popular products").
What is the correct way with CakePHP to achieve this?
At the moment I created a mostPopularList() in my Product controller and a most-popular-list.ctp view that only outputs an <ul> list, thinking that then I could include the output of this file in my layout (default.ctp), but I didn't find the CakePHP way to do that.
Thanks!
Use a view cell or call the query in the AppControllers beforeRender() callback and set it there to the view. Taken from the documentation:
View cells are small mini-controllers that can invoke view logic and render out templates. They provide a light-weight modular replacement to requestAction(). The idea of cells is borrowed from cells in Ruby, where they fulfill a similar role and purpose.
View Cells
Controller::beforeRender()
If this is needed on really every single page I would probably go for the beforeRender() callback, easy to do and change globally.
I'm new to PHP and I am currently creating a PHP web application for an assignment at university. During the development I had realized that alot of elements in the user interface were being replicated in different sections of my application. For example I may have a hyperlink button in a Clients Page called 'New Client' (<a class="bigbutton" href=".......">New Client</a>) and another hyperlink button in a projects page called 'New Project' (<a "bigbutton" href=".......">New Project</a>).
Normally, I could just copy the html that constructs the buttons on the Clients Page and Change the content to suit the 'New Project' button in the projects page. Now If I was convert the hyperlink button to the tag, I would have to go to every instance of that particular button to replace the tag with a tag and if this button exists on so many pages, then updating would be time consuming.
That was just a simplistic example, then I have to think for other repeated elements across multiple pages such as breadcrumbs, list tables etc.
Is there any way to code in a way where I can actually reuse these UI elements that may be worthwhile to look at? Perhaps I could try to code each of these elements into classes, but right now I am not sure.
Any hints, pointers or resources would very helpful and appreciated.
Thanks guys.
You can make PHP functions which echo the HTML when called, optionally including some config stuff e.g.
function make_button($id, $label) {
echo '<button id="'.$id.'">'.$label.'</button>';
}
This can be done for large chunks of the page, or just small bits. Some systems I've used have a html_writer class for this sort of thing, others use render methods where you pass an object in and it'll pass back a string of HTML representing that object on a page.
Up to you which you prefer. Also good to make small functions which can be reused in larger functions like:
function make_buttons_from array($array) {
foreach ($array as $id => $label) {
$this->make_button($id, $label);
}
}
The examples here echo their output, but you can also use string concatenation to assemble the pieces. Again, your call. There's not really a right way.
There's all sorts of specific avenues you could take, but the basic approach is to have a set of templating functions or methods in a class that build all of the common elements of your pages. Anything that's shared (or has only minor changes) from page to page is defined once in these functions, and you simply call the functions from each page, providing enough information to allow the function to differentiate how it should display its content depending on the details of the page that's calling it.
If you've got a change to a common element, you just go to the function and change it, and in this manner it's copied to all of the pages.
I am trying to create multiple landing pages populated dynamically with data from a feed.
My initial thought was to create a generic php page as a template that can be used to create other pages dynamically and populate them with data from a feed. For instance, the generic page could be called landing.php; then populate that page and other pages created on the go with data from a feed depending on an id, keyword or certain string in the url. e.g http://www.example.com/landing.php?page=cars or http://www.example.com/landing.php?page=bikes will show contents that are either only about cars or bikes as the case may be.
My question is how feasible is this approach and is there a better way to create multiple dynamic pages populated with data from a feed depending on the url query string or some sort of id.
Many thanks for your help in advance.
I use this quite extensively. For example, where I work, we often have education oriented landing pages, but target each landing page to different types of visitors. A good example may be arts oriented schools looking for a diverse array of potential students who may be interested in a variety of programs for any number of reasons.
Well, who likes 3d Modelling? Creative types (Generic lander => ?type=generic) from all sorts of social circles. Also, probably gamers (Gamer centric lander => ?type=gamer). So on.
I apply that variable to the body's class, which can be used to completely reorganize the layout. Then, I select different images for key parts of the layout based on that variable as well. The entire site changes. Different fonts can be loaded, different layout, different content.
I keep this organized via extensive includes. This sounds ugly, but it's not if you stick to a convention. You have to know the limitations of your foundation html, and you can't make too many exceptions. Sure, you could output extra crap based on if the type was gamer or generic, but you're going down the road to a product that should probably be contained in its own landing page if it needs to be that different.
I have a few landing pages which can be switched between several contents and styles (5 or 6 'themes'), but the primary purpose of keeping them grouped within the same url is only to maintain focus on the fact that that's where a certain type of traffic goes to in order to convert for this specific thing. Overlapping the purpose of these landing pages is a terrible idea.
Anyway, dream up a great template, outline a rigid convention for development, keep each theme very separate, and go to town on it. I find doing it right saves a load of time, but be careful - Doing it wrong can cost a lot of time too.
Have a look at htaccess URL Rewrite. Then your user (and google) can use a url like domanin.com/landing/cars but on your server the script will be executed as if someone entered domain.com/landing.php?page=cars;
If you use feed content to populate the pages you should use some kind of caching to ensure that you do NOT reload all feed on every requests/reloads the page.
Checking the feeds every 1 to 5 minutes should be enough and the very structure of feeds allows you to identify new items easily.
About URL rewrite: http://www.workingwith.me.uk/articles/scripting/mod_rewrite
A nice template engine for generating pages from feets is phptal (http://phptal.org)
You can load the feet as xml and directly use it in your template.
test.xml:
<foo><bar>baz!!!</bar></foo>
template.html:
<html><head /><body> ${xml/foo/bar}</body></html>
sample.php:
$xml = simplexml_load_file('test.xml');
$tal = new PHPTAL('template.html');
$tal->xml = $xml;
echo $tal->execute();
And it does support loops and conditional elements.
If you are not needing real time data then you can do this in a few parts
A script which pulls data from your rss feeds and stores the data somewhere (sql db?), timed by something like cron. It could also tag the entries into categories.
A template in php taking the url arguments and then adding the requested data and displaying it for the user. Really quite easy to do with php, probably a good project to use to learn as well if you are that way inclined
I have spent a good proportion of time today looking into expanding a drupal site I inherited, convinced that the issues I face were down to my bespoke SQL query.
I have since realised that the SQL is ok (checked it in PHPMYadmin and got it executing of sorts within the drupal website). So I am happy I am getting all the results from the database I need, looping through them and outputting them on the page in the specific markup.
The problem I have is where the loop is displaying. I cannot seem to figure the theming system or understand what is going on in template.php.
Let me explain:
The code I needed to change was in the template.php file. My understanding is that this file allows you to overide certain functions and theme elements.
Within the template.php file this is the code I needed to change:
//old function from original development
function abc($node,$submitted,$node_url) {
//execute code
}
So I added my code within function abc(), as I wanted it to be output where the old code was output.
This is my psuedo code for the sql and the loop:
function abc($node,$submitted,$node_url) {
$sql = 'my sql query'
$results =db_query($sql);
while ($data = db_fetch_array($results)) {
//output my results here
}
}
What led me to believe that the sql was wrong is that I should have got 23 results, but I was getting a lot more duplicate entries. After wasting alot of time looking in the wrong place, and scrutinising the sql, I realised that it was the function executing the sql and the loop multiple times, not the sql returning duplicate entries. I did this like so:
function abc($node,$submitted,$node_url) {
$sql = 'my sql query'
$results =db_query($sql);
$x = 1;
while ($data = db_fetch_array($results)) {
if ($x == 1) {
echo '<p style="background-color:#ccc;">'. $x . '. '.$data['title'] . '</p>';
}else{
echo '<p>'. $x . '. '.$data['title'] . '</p>';
}
$x = $x + 1;
}
}
As the code executed I was expecting an incremented number to go on for as many duplicate entries and shade the first entry's background to grey, but it did not. At result 23, it reset itself to 1 and shaded that entry's background to grey, indicating to me that it was the function executing the sql and the loop multiple times.
I am not wholly sure what this abc() function is, apart from the fact that when I place my code within it, the output displays where I need it to on a specific page and nowhere else (with no duplicate entries).
When I take my code out of this function (still within template.php), my code is output in the head of all pages which is not desirable.
Does anyone have any ideas as to what might be happening, where I can look to find out what this function is or know of a way for me to determine the display of my code?
I have been reading a bit about themes etc, but working with someone else's code is turning into a bit of a confusion nightmare.
Cheers in advance!
You are down the wrong path here, probably because you are inexperienced in how Drupal works, so let me give you some info and advice.
You could say that Drupal have to layers in which it execute code, the modules/core and the theming. Generally you could say that the first layer, the modules/core is the generation/fetching of data, while the 2nd is the presentation of that data. What you are doing is fetching data in the presentation layer, which really should be avoided. This is also the reason why you had so much trouble tracking down the cause, because of the confusion of what is getting the data and what is presenting it. What you did is also very much a waste of resource, I'll come to that later, but first what happened?
You have taken over a site, which probably have a custom theme, and I can tell that it has been made in an hacky way. Maybe the one who did it, didn't know the proper way but made something that “works”. Now what trying to alter it, you broke it. When Drupal presents a node (a node is a piece of content), it gets a lot of data, modules can hook in and add, alter or delete that data, and in the end the data gets to the template (all template files are denoted tpl.php - that is unless a different template engine is used). The way this works, is that it uses the “page” template to create the basics of the site, the navigation, the different regions ect. Now when displaying a list of nodes, each node will be displayed within the page template by having it's data outputted to the node template. Normally there's a lot of divs ect. combined with some php printing of data. In your example a function was also called. In some cases this can be fine, if you use fx translate functions for multi lingual sites or a simple function that checks something for you. However in your case you used that function to get data. By looking at the SQL you created it seems like you actually was trying to get the list of blog nodes you wanted to show. This could kind of work if only a single node was displayed, but when a list of nodes are displayed, you run the SQL and print the result for every node listed which is what got you in this mess. This is also very ineffective, as you run the query each time the node template is used. As you can see, it's very confusing and hard to control fetching data in the theming layer. But how do you do it then?
There are some different ways to do things kind of things, there are even made modules for this. Now it seems you want to display a list of blog nodes based on 2 CCK date fields.
The easy non coding way:
Simply create a view, using the views module. You can select nodes of type blog and filter based and the current data and the date on the cck fields. You can choose different displays. Showing either the full node or only part of the node, list, table ect. Lastly you select an URL for the view and you're done.
The harder coding way:
Create a custom module. First you need to implement hook_menu() to create a menu item which is how you setup the URL. Doing that you assign a function that you must create for that URL. In it you put much of the above code, fetching the data with SQL, however you will also need to run that data through various theming functions that will generate the markup and lastly you return the data. This is actually quite easy to do, if you know how Drupal works. If not, it will be hard to do this properly as you will need to call a lot of functions you don't know, and implement hooks ect.
This ended up being a bit longer than I planed, but I hope it helps you out with your new Drupal site.
Edit:
It actually looks like the SQL you posted is the SQL generated from a view that looks to be working. The only flaw is that you ask for both date fields to be greater or equal to now. CCK fields can have a default value but I believe you can always edit it to whatever you like when you edit the node, unless the node form has been edited to hide the fields. Also there wouldn't be any reason to use a CCK date field for the publish date. That information is available on every node along with last edited date.
You can find a lot of good stuff at Lullabot. They have made a lot of stuff on how to use CCK and views. Some of it they sell and some of it you can get for free. In your example, the difficult part is getting the nodes you want. To do that you need to add filters. When you want to sort by any date, you need to add a date filter located in the date group. In it you can check the fields you want to use. However in your case you want to add the date filter twice one for each of the date fields, as you have different values for the fields. This is probably where your flaw is and what is giving you problems.
Just to clarify my comment, it should look something like this:
function getData(){
$sql='my sql query';
results =db_query($sql);
$return_string = '' ;
while ($data = db_fetch_array($results)) {
//Loop through data and save to $db_data
$return_string .= $db_data;
}
return $return_string;
}
It sounds like you're on the right track with calling this function from within page.tpl.php; note that you can have it display only on specific pages by conditionally invoking it for specific values of $node->nid:
<?php if ($node->nid == xxx || $node->nid == yyy) print getData() ;?>
If you're using CCK and displaying the results of your function for specific content types only, Contemplate is a good module, esp. for beginning Drupalers, that makes some of this easier.
Well, to start, you shouldn't use echo, since it will print when the code is run (e.g. at the top of the page while it's loading) rather than into the variables that the template displays at the appropriate spots in the page. (This isn't to say that echo won't ever work, but using it isn't best practice.)
What did the previous function use to output the data? (There might be a page named something like abc.tpl.php (if your function is named abc) that will help you find the appropriate variable names.
If you add the SQL strings you were using, I might be able to diagnose that issue as well.
EDIT:
Assuming, based on your earlier comment, that you are trying to format a blog node (I base this on your mentioning the lack of a node-blog.tpl.php):
Drupal's assumptions, when rendering a page, go something like this (simplified):
Load the core. Grab the content from the database. Get the taxonomy and other goodies, and make these available to the modules and themes
Then, look in all the modules to see
if they have hooks that, based on
their function name, will modify the
page. If they do, run the functions.
If they don't, leave the page alone.
Then, look in all the theme to see
if template.php have hooks that,
based on their function name, will
modify the page. If they do, run the
functions. If they don't, leave the
page alone.
Last, look at the tpl.php files and display the page using those. If there's no tpl.php file with the right file name, then load it using node.tpl.php
A good summary of all that is at http://drupal.org/node/173880
If you have no functions in template.php that look like the would modify the page, and you have no tpl.php files that match the node you're looking for, that means that all your pages are being loaded using the default template.
(This is probably why your predecessor set up the strange construction that he did. Using a function like that is a kinda hacky way to do what Drupal can do automatically through the theme functions)
So:
Go ahead and make the tpl.php file. Call it node-blog.tpl.php if your content type is a blog node, or something else. You can probably just copy the existing tpl.php files for now. Then, create a preprocess function in template.php to go along with it.
(You will need to rebuild the theme registry for Drupal to recognize the changes -- you already have the Devel module installed, so it should be easy from there. Visiting /admin/build/modules on your site will work as well.)
Then, visit http://drupal.org/node/223430 and http://drupal.org/node/337022 for some quick explanations and code snippets that will let you pass your data as a variable, that the template can then render on your pages
One Last Edit:
By any chance, does this function build a list of blog posts, and present the information in summary form (e.g. a list of pending posts)?
I ask because if so, the Views module can probably do all of this work for you. Unless the data processing in function abc() is really, really, fancy, this seems like just the sort of thing that Views was built for.
While template.php is used for overriding various theme functions it can also be used to simply store functions that are called on your templates (you can also force template.php to be available in a custom module depending on how hacky the site was done by the original developer(s)). So just because a function is in template.php does not automatically assume it is a theme override (if you can provide he actual name for the function it would help to determine if it is though).
And the reason taking your code out of the function but leaving it in template.php causes the output on every page is because template.php is included in every page. Theoretically you can put more than just functions in template.php. On a large site I worked on one of the developers broke up the functions into a couple smaller files so template.php was just 2 or 3 functions and 3 or 4 include()'s.
Knowing the actual name of the function would really help determine if this is a custom function or a theme override.
To answer a few questions you have raised:
The previous function was doing this:
function abc($node,$submitted,$node_url) {
echo $node->taxonomy['color'];
$a = explode(",",$submitted);
$b = explode("-",$a[1]);
// THIS IS THE DESCRIPTION
if(strlen($node->content['body']['#value'])>180)
{
$c = str_split($node->content['body']['#value'],180);
$d = $c[0]."...";
}
else{
$d = $node->content['body']['#value'];
}
$multiple = $node->field_mul_event[0]['view'];
$eventcode = $node->field_event_code[0]['value'];
$strdata="";
$strdata.="specific markup to output here";
return $strdata;
}
This functionjust pulled out a start and end date and a description
The sql string in my code is:
select DISTINCT node.nid AS nid, node.title AS node_title,
content_type_blog.field_date_from_value AS node_data_field_date_from_field_date_from_value,
DATE_FORMAT(content_type_blog.field_date_from_value, '%%d/%%m/%%Y') AS dateFrom,
content_type_blog.field_date_from_value2 AS node_data_field_date_from_field_date_from_value2,
content_type_blog.nid AS node_data_field_date_from_nid,
field_mul_event_value AS multiEvent,
field_event_code_value AS eventCode,
node.type AS node_type,
content_type_blog.field_event_excerpt_value AS node_data_field_date_from_field_event_excerpt_value,
image_attach.iid AS image_attach_iid,
node_images.filepath AS imagePath,
color AS catColour
FROM node
node LEFT JOIN content_type_blog content_type_blog ON node.vid = content_type_blog.vid
LEFT JOIN image_attach image_attach ON node.nid = image_attach.nid
LEFT JOIN node_images node_images ON node.nid = node_images.nid
LEFT JOIN term_node term_node ON node.nid = term_node.nid
LEFT JOIN term_data term_data ON term_node.tid = term_data.tid
WHERE node.type LIKE 'blog' AND content_type_blog.field_date_from_value >= DATE(NOW()) AND content_type_blog.field_date_from_value2 >= DATE(NOW())
ORDER BY content_type_blog.field_date_from_value ASC
As I am sure you can tell, this sql grabs all the same data (and some extra info) except data older than todays date and then orders it in date order.
I have taken a look in the theme folder and there are two tpl.php files with the same code in them:
<?php print $fields['title']->content; ?>
<?php print $fields['introduction']->content; ?>
I cannot see any custom modules as such in sites/all/modules. This is the list in there (but they all seem like inherent modules to me):
cck
date
devel
extlink
fckeditor
image
imce
menu_breadcrumb
nice_menus
node_images
pathauto
sections
swftools
token
views
wysiwyg
Excuse my ignorance - but I am learning drupal as I go along. More of a wordpress gal usually if you know what I mean. Not used to nodes/taxonomy/the drupal system and the like which is my base excuse for my lack of knowledge.
I need to find that function and determine what it does - gah!!!
Thanks everyone!
Ok had a look about using the theme developer:
Parents: theme_taxonomy_term_page < page.tpl.php
Template called:
node.tpl.php
File used:
modules/node/node.tpl.php
Candidate template files:
node-blog.tpl.php < node.tpl.php
Preprocess functions:
template_preprocess + template_preprocess_node + content_preprocess_node + nodereference_preprocess_node + views_preprocess_node
Duration: 6.84 ms
Look in here modules/node/node.tpl.php and found references to abc function
<?php print abc($node,$submitted,$node_url); ?>
Can't find node-blog.tpl.php and can't find any references to functions template_preprocess + template_preprocess_node + content_preprocess_node + nodereference_preprocess_node + views_preprocess_node
Stumped.
A very good start to see what's going on with the theme hooks and template files is the devel module. Enabling it and going to the site and enabling the "Theme Developer" module will get you a little widgety thing in the bottom left part of your pages, where you can check a box and then click on any element on the page - and it will show you what it is executing, why, and what else it could be executing.
Could be a start.