I'm writing a project in php that will basically give me a webpage with links to things like:
a page containing my favorite youtube videos stored in a mysql db
a page with all my favorite games
and music ect
All will be embeded directly inside the webpage rather than linking to the site.
To simplify this I've made a master template "index.php" and then using $_GET I pass pages and other info through to the template which is then handled by a page check script which performs a number of ifs to determine what php script to load into the website.
Where my question lies is whats the prefered method for loading theese scripts into the website as my current method is
if ($_GET["page"] == "videos"){
include ("dynapage/scripts/videos/videos.php");
}
if ($_GET["page"] == "music"){
include ("dynapage/scripts/music/music.php");
}
ect
Is using includes to add this code into my template a good thing to do or is there a better method you can suggest?
note: checks for isset are already included in the checks and aditional pbs are availble on request.
Use an array which has the $_GET["page"] value as key and the php filename as value. You then only need to check if it is inside the array and if so, include it. You then write the values into the array instead of writing many if clauses.
The following code example shows this, additionally it has a function to load a page because so the included script does not set variables in the context it gets included into by accident.
$pages = array(
'videos' => 'videos/videos.php',
'music' => 'music/music.php',
);
/**
* include a page template
*/
function load_page(array $pages, $page, $path = 'dynapage/scripts')
{
if (isset($pages[$page])) return;
include ($path.'/'.$pages[$page]);
}
if (isset($_GET['page']))
{
load_page($pages, $_GET['page']);
}
Maybe Something like this:
$config = array(
'videos' => 'dynapage/scripts/videos/videos.php',
'music' => 'dynapage/scripts/music/music.php'
);
if(isset($config[$_GET['page']])) {
include($config[$_GET['page']]);
}
is a bit better, then writing many if clauses (;
Looks like you can just do:
if( file_exists($fn = "dynapage/scripts/".$_GET['page']."/".$_GET['page'].".php"))
include($fn);
Related
**also posted on druapl.stackexchange
https://drupal.stackexchange.com/questions/150500/giving-custom-argument-vlue-in-q-variable
**
apologies if question is ambiguous . the scenario is as follows:
in drupal 7 , we want to use a custom template page when a specific value is given for the q variable in url .
for example if we give http://localhost/drupal/?q=xyz/123 , we want to use a custom template page say page-xyz.tpl.php ..
have a hunch that hooks and template.php file may be the key components here but not sure what to exactly do..
any help appreciated.
you could implement theme_preproccess_page() (or node, or html) to control this in your template.php
function YOURTHEME_preproccess_page(&$vars) {
if (isset($_GET['q']) && $_GET['q'] == 'xyz/123') {
$vars['theme_hook_suggestions'][] = 'page_xyz';
}
}
that should work, but I would like to recommend not use the '?q=xyz' solution, but do an preproccess that should work to all your pages, like this.
function YOURTHEME_preproccess_page(&$vars) {
$title = strreplace(' ','_', $vars['node']->title);
//if you use the transliteration module, instead of strreplace
//use transliteration_get($vars['node']->title);
$vars['theme_hook_suggestions'][] = 'page_'.$title;
}
now that should work for every page that you want to make a custom template. Just add the file and clear the chaches. If you don't have the page template to the specific page, it's ok, drupal will use the default.
With Drupal 7, I have a content type with multiple fields. I then have a view page that takes this content type and displays all the content on it.
So think of it like a blog.. and then a main blog display page.
I have it set so that a menu item is automatically created in the proper place.
I also have Pathauto set up so that it creates a link
www.site.com/blog_anchor_node-title
The individual content page will never be accessed, so I'm not worried about the strange url, however, since hashtags are not supported by pathauto, I used anchor
I need every instance of anchor to be replaced with a # via the template.php file.
This will allow anchor tags to automatically be added to my main menu, the footer, as well as jump menus on the "blog" page it's self.
so far, the closest thing I have is:
function bartik_theme_links($variables) {
$links = $variables['links'];
if (!(strpos($links, "_anchor_") === false)) {
$links = str_replace("http://", '', $links);
$links = str_replace("_anchor_","#",$links);
} }
This doesn't work.
First, your theme_links implementation should not include theme in its function name. And second to quote the documentation page linked before, `$variables['links'] is …
An associative array of links to be themed. The key for each link is used as its CSS class. Each link should be itself an array, with the following elements
Your replacement does not work because you're using strpos on an array.
To make this work go to the API documentation page, copy the code (yes the hole code) and just insert something like the following at the beginning:
function bartik_links($variables) {
$links = $variables['links'];
foreach($links as $key => $l) {
// do your replacements here.
// You may want to print out $l here to make sure
// what you need to replace.
}
//...
}
Also make sure the function is named properly.
To allow me to use the # symbol in a URL, what worked for me was adding the following to my template.php file (before the function above you want to call). You don't have to change anything else besides YOURTHEMENAME to your theme's name:
function YOURTHEMENAME_url_outbound_alter(&$path, &$options, $original_path) {
$alias = drupal_get_path_alias($original_path);
$url = parse_url($alias);
if (isset($url['fragment'])){
//set path without the fragment
$path = $url['path'];
//prevent URL from re-aliasing
$options['alias'] = TRUE;
//set fragment
$options['fragment'] = $url['fragment'];
}
}
Ok, here's the deal: I am constructing a Drupal website that has several different sections. Each section is a view that displays a content type. (Each section has it's own content type) For example, I have a view that points to ?q=blog which displays content type blog.
All the sections look a little different than each other. Not like 'website-within-a-website' different but different enough that they can't all use the same template file and each be modified with CSS. Each section needs it's own page.tpl.php.
Unfortunately, AFAIK Drupal theme's .info files can only either assign one page.tpl.php for the entire theme or assign a page-node-####.tpl.php for each node. There is going to be lots of content on this website so setting Drupal to make a new identical page-node-####.tpl.php for every created node would get unmanagable very fast.
To solve this problem, I am going to use pathauto to create an alias for each content type. For example, all nodes of content type blog are given an alias ?q=blog/[post title]. Modify template.php to use page-blog.tpl.php for any page who's alias starts with the word 'blog'.
Other people have tried doing this sort of thing and have created functions such as the one described. Unfortunately, all the ones I have seen are for Drupal 6 or below. I have tried modifying existing ones with no success. So far, though, I think this is on the right track:
function basic_preprocess_page(&$vars, $hook) {
...
if( module_exists('path') ) {
$alias = drupal_get_path_alias( $_GET['q'] );
$site_section = "blog";
if( strpos( $alias, $site_section ) === 0 ) {
$VARIABLE_THAT_TELLS_THE_PAGE_WHAT_TEMPLATE_TO_USE = "/path/to/page-blog.php";
}
}
}
I cannot find $VARIABLE_THAT_TELLS_THE_PAGE_WHAT_TEMPLATE_TO_USE does anyone know what it is?
Maybe my site is structured badly. If anyone knows how to restructure my site so I can more easily make a theme with seperate sections please share how!
Thanks a million! (c:
EDIT: Perhaps I need to use template suggestions instead. Does anyone know the function or variable to use to set this?
They changed the name of this array key in D7 and I haven't seen it documented anywhere. I finally figured this out after a good bit of debugging. You can override the theme template in template.php with a hook_preprocess_page() like so:
function myTheme_preprocess_page(&$vars) {
global $node;
if ($node->type == 'blog') {
$vars['theme_hook_suggestions'] = array('my__blog_template'); // use my--blog-template.tpl.php, note '-' = '_'
}
elseif ($node->type == 'articles') {
$vars['theme_hook_suggestions'] = array('article__node_template'); // use article--node-template.tpl.php
}
}
Oh and don't forget to flush the Drupal caches after making changes to your template.php.
Ok, I found it:
http://drupal.org/node/223440#comment-991840
$alias = drupal_get_path_alias($_GET['q']);
if ($alias != $_GET['q']) {
$template_filename = 'page';
foreach (explode('/', $alias) as $path_part) {
$template_filename = $template_filename . '-' . $path_part;
$variables['template_files'][] = $template_filename;
}
}
Credit to this function goes to user mfb.
I had a lot of trouble with this so I will explain it here in case anyone finds it useful.
This function goes in your template.php. It needs to be part of the <theme name>_preprocess_page function. What it does is it takes the alias and then explodes it into a bunch of different components. For example if you are on a page with the alias ?q=blog/blog-post-title it would be exploded into blog and blog-post-title. It then turns each component into a name for a template suggestion. It puts each template suggestion into the template_files[] array (inside the $variables[] array) so that the page now has two new template suggestions:
page-blog, and page-blog-blog-post-title
Template suggestions are alternate template files. In this case they are for pages, but they don't necessarily have to be. You can have template suggestions for anything you can think of including blocks, nodes and the like. Don't let the name 'template suggestion' fool you. Template suggestions will be used over default templates as long as they exist. I don't know why it was named like that. I think it should be renamed.
What you do, then, now that you've set up Drupal to look for a template suggestion that points to your alias, is create a new template file where all the rest are in your theme. In this case, let's say I want to theme my entire blog section. In the templates folder I should create a file named page--blog.tpl.php (note the --double hyphens--) with the layout I want.
Drupal will use the most specific template suggestion it can find so if you wanted you could make one blog post to look completely different than the rest of the site long as you make a template for it named page--blog--blog-post-title and put it in your theme's templates directory. (again, note the double hyphens.)
Ok for sure this has been asked and answered already but i somehow can't find a proper tutorial.
I want to keep the text displayed to users somewhere else and to prevent my code from becoming too large and unreadable.
My site won't be internationalized. I just want to have some kind of file with key-value structure and get the text from there. I want to keep the text in files, not in the database as some tutorials suggest.
I found a solution which will work but i am not sure whether this is a good approach.
I am thinking of using parse_ini_file and to keep my texts in .ini file. Is there something wrong with this approach? Could you suggest something better?
I put all language data in arrays. Its easy and also we can add multi-language support
lang/en.php
<?php
return array(
'index' => 'Homepage',
'feedback' => 'Feedback'
'logout' => 'Logout from profile',
)
?>
lang/ru.php
<?php
return array(
'logout' => 'Выйти из профиля',
)
?>
Then we can load languages:
$lang = include('lang/en.php');
if(isset($_GET['lang']))
{
$lang = array_merge($lang, include('lang/ru.php'));
}
After all it $lang will look like:
Array
(
[index] => Homepage
[feedback] => Feedback
[logout] => Выйти из профиля
)
And we can very simple use it:
function __($name) {
global $lang;
return $lang[$name];
}
Somewhere in the site template:
...
<title><?=__('index')?></title>
</head>
<body>
<?=__('feedback')?>
why not use a plain text file with commas or some uncommon character to hold this data? you can read it and parse it into an array with
$file = file_get_contents("/path/to/file");
$lines = explode('\r', $file);
foreach($lines as $line) $message[substr($line, 0, strpos($line, ','))] = substr($line, strpos($line, ','));
then you should have an array like $messages[3] = "No soup for you!";
the file might look like:
1,The site is down.
2,Try again.
3,No soup for you!
4,Signs point to yes.
(I probably have some of the arguments misplaced in those functions - i always forget which is the needle and which the haystack.)
You can process your data in a script. In this script, you call a certain source (e.g. the ini file you suggest). Then you use a template engine. For this engine, you point towards a template file and give the template all the variables.
The template generates the html and inserts the variables at the right place. This way, you keep you php (business logic) code clean, away from the presentation (the template). Also you can manage the variables in one file (ini/xml but this can be something completely different).
For template engines, Smarty is the most known of all. There are also pure php-based template systems, just Google for them to find one that suits your needs.
I do like this:
$defaultLang = array('Home','Logout',etc)
$otherLang=array( 'ru' => array('Home_in_ru','logout_in_ru',etc);
you translate like this:
echo translate('Home');
function is:
function translate($msg) {
if ($_GET['lang']=='en')
return $msg;
return $otherLang[$_GET['lang']][array_search($msg,$defaultLang)];
}
// Note the function is simplified up there
As you can see the default case deosnt' need to load anything or do any operation, the function just returns back the argument passed
i like the answer with the lang/en.php file. but instead of a file for each language, i use a file for each web page (or class, etc). this keeps file sizes lower and i create a 3D array:
`return array( "EN" => array( "title" => "Welcome - Good Morning", ...),
"TG" => array( "title" => "Mabuhay - Magandang Umaga Po", ...)
);'
Real easy to add new language strings too...
This makes it real easy for language translation contractors since they can see the native language in close proximity to the foreign in 1 editor,,,
I was wondering what the filter was to change the search term in Wordpress?
For example, if someone types in xxx, how could I change that to yyy before it goes into the wordpress search engine?
Cheers.
Change it when it gets to WordPress, right before WP queries the database:
$search_replacements = array(
'find' => 'replace',
'find2' => 'replace2',
'var' => 'foo'
);
function modify_search_term($request_vars) {
global $search_replacements;
if (!empty($request_vars['s']) && !empty($search_replacements[$request_vars['s']])) {
$request_vars['s'] = $search_replacements[$request_vars['s']];
}
return $request_vars;
}
add_filter('request', 'modify_search_term');
This will allow you to handle as many conditions as you can think up and add to the $replacements array.
The 99 in the add_filter is to get it to run late so that you're the last one to make changes to the query (could be important depending upon what other plugins you have installed).
Your URL will still indicate the original term, but you save a page load. If you have a high traffic site then you don't want to redirect just to get a pretty url.
Your not going to be able to change it before it goes into wordpress without using htaccess rewrite rules. What you can do however is create a custom filter to manually redirect specific search terms into new search query's using a standard browser redirect. I had to use the javascript location function in my example because I couldn't figure out how to catch the search variable via a filter before anything was outputted to the browser (thus limiting my ability to use the built in wordpress redirect function or a standard php header redirect.)
The following code will take any searches for "test" and redirect it to a "smickie" search. This was put together pretty quick and dirty, so you'll want to modify it to suite your needs obviously, but hopefully this can get you started in the right direction.
function redirect_searchterm() {
if (is_search()) {
$search_query = get_search_query();
if ($search_query == "test") {
$new_searchquery = "smickie";
?>
<script type="text/javascript">
<!--
location.replace("<?php echo get_option('siteurl') . '/?s=' . $new_searchquery .'&submit=Search'; ?>");
-->
</script>
<?php
}
}
}
add_action('wp_head', 'redirect_searchterm', 1);