I'm new to PHP and want to apply a specific class to the title of my page depending on what part of the site the viewer is browsing.
For instance, I want to apply the class "blog" to the if the viewer is at domain.com/blog OR domain.com/blog/post-1 so on and so forth BUT apply the class "pics" if they're viewing domain.com/pics or domain.com/pics/gallery-1 etc etc.
I found something that could be modified to serve my needs using javascript here
but I figured seeing as I'm using PHP already, it'd make more sense to keep this sort of thing server side.
As I say, I'm new to PHP. I've experimented with some regular expressions, but to no avail.
EDIT: Sorry not to be more specific in my first post, I am using wordpress as my CMS - this is my first stackoverflow post, I trust you can forgive me :)
<?php
if (substr($_SERVER['REQUEST_URI'], 0,5)=='/pics') {
$h1class='someclass';
}
The it depends on how you're putting the class in the tag, might be like this
?><h1 class="<?php echo $h1class; ?>">...
Rather than putting a class in based on the page, I would suggest having seperate CSS files for home.css, blog.css, whateverelse.css. Of course, these would be in addition to some sort of default.css or site.css or whatever that would contain the styles used across the site.
You can then build a function/method to create the CSS calls in the HTML header. I usually have a "Page" object that builds the actual HTML page, and a "get_css" method that spits out the CSS calls.
It's hard to get more specific without knowing how you currently build pages.
Here is the solution I ended up crafting. Credit to #m.buettner for pointing me towards explode().
<h1 id="title-text" class="
<?php #returns the category as a class
$url = array();
$url = explode('/', get_permalink());
echo $url[3];
?>
mono in-case-404">
SITE
</h1>
Related
I am trying to create a function that can inject HTML in between certain div tags using PHP.
For example lets say I have the function with the following parameters. add_html('<div class = "greeting">', 'hello')
How would I make it so that the text hello was added inside of <div class = "greeting"> like so: <div class = "greeting">hello</div> My goal is to use PHP for this. How would I go about implementing this? What would be the most simple way to accomplish this?
A function could be like so:
<?php
function add_div($class, $content) {
return sprintf('<div class="%s">%s</div>', $class, $content);
}
echo add_div('foo', 'Hello Earth!');
Output:
<div class="foo">Hello Earth!</div>
But it doesn't really save you much typing.
You've changed the particulars of it, but the fundamental issue remains unanswerable with any kind of specifics that it seems you're looking for. I am struggling to even express how many variables there are in what you're asking. I'm putting this as an answer, not because it answers your question, but because comments are insufficient to address it.
Your current example is that you want a "greeting" div. Okay. But where do you want it? On every page? On the home page? At the top or bottom or somewhere in between? Let's assume that your CMS has a way of knowing what overall layout is going to be used (headers, footers, menus, sidebars, etc.), and what specific template is going to be used to generate the page-specific content (text and pictures of a blog post, for example), and that you want to give your plugins a way to inject their own content into the layout right at the top of the content (above the blog text and pictures). This is now a nice, specific sort of question that StackOverflow is better at answering, instead of such a general open-ended one that you have.
Okay, let's address that particular question. Ideally, you would show your CMS code for generating a page. Let's pretend it's something like this:
echo $this->layout->headers();
echo $this->layout->menu();
echo $this->template->content();
echo $this->layout->footers();
It's probably actually more complex than that, but this will do for an example. Now, we can say that if you want to use a plugin hook architecture, you would add something like this after the menu call:
foreach ($this->plugins as $plugin) {
if (method_exists($plugin, 'inject_pre_content')) {
$plugin->inject_pre_content();
}
}
and you would add an inject_pre_content function in your plugin which echoes your desired HTML.
If you wanted to use event hooks instead, then in the same place you might instead simply add:
$this->triggerEvent('inject_pre_content');
but this relies on you also incorporating an event handling framework.
Plugin hooks are, IMO, easier to build, but not as powerful.
Hope that this helps you to understand what you're up against a little bit better, and clarifies what the two main options might look like.
To begin, I'm sorry if the title is misleading. I find it hard to put it into words.
My question is regarding websites that have a lot of pages that are structurally identical, but the content is different.
Take Facebook as an example. Every person's profile is a "/profile.php" of some sort, but depending on whose profile you're viewing, the content is different.
It seems to me like there is one single .php-file for a profile, which loads content based on a profile ID in the database.
So, the question:
Certain types of CMS, like Drupal, do this. You create a node, and it has some content. You create another node of the same type, with different content, but it certainly doesn't create a brand new .php-file on your server for every single node, right? What's the process here? Can I program this using PHP?
I'm very much a beginner at PHP, but I'd very much like to learn how to achieve this practically.
Also, before any sarcastic "just use Drupal" comments arise, keep in mind that I do use that already, but again, I want to see if I can learn how to do this myself.
You can do this either on the server side using PHP or client side using JavaScript:
Server side using PHP:
If you navigate to a url like this: http://example.com/p.php/someParameter, it will actually go to p.php, but the entire uri is available at $_SERVER['REQUEST_URI'], so you can strip ot the someParameter part and serve content dynamically. This would look something like:
<?php
$title = '';
$content = '';
$uri = $_SERVER['REQUEST_URI'];
$slash = strrpos($uri, '/');
$parameter = substr($uri, $slash + 1, strlen($uri) - $slash);
// Update the title and content based on the parameter
?><html>
<body>
<h1><?php echo $title; ?></h1>
<div><?php echo $content; ?></div>
</body>
</html>
Client side using JavaScript
If you are happy to have the # in your path, there are various JS libraries that can make this quite easy as well. I use Knockout and Sammy.js. For a tutorial on how to do that, check out the knockout tutorial.
I am creating breadcrumbs on my simple site.
I have some helper classes. I use them like this (just example):
$Breadcrumbs = new Breadcrumbs();
$Breadcrumbs->add(new Breadcrumb("/", "page1"));
$Breadcrumbs->add(new Breadcrumb("/", "page2"));
$Breadcrumbs->add(new Breadcrumb("/", "page3"));
$breadcrumb->show(); returns this:
<ol class="breadcrumb">
<li>page1</li>
<li>page2</li>
<li class="active">page3</li>
</ol>
So, in my project I have some switch-case constructions in which I include some files.
In this files I am using $breadcrumbs->add(...). This code:
<div class="container body">
<? $Breadcrumbs->show();?>
<?
$page = isset($_GET['page']) ? $_GET['page'] : null;
switch($page):
case "suppliers":
require_once($DOCUMENT_ROOT."/modules/suppliers.php");
break;
default:
require_once($DOCUMENT_ROOT."/modules/default.php");
break;
endswitch;
?>
<? $Breadcrumbs->show();?>
</div>
gives me this result:
Well, it works like it must work. I am using $breadcrumbs->add(...) in require files after I called $breadcrumb->show() first time thats why 1st call returns blank result. 2nd call of show() is after all breadcrumbs are added, so it returns fine result.
The questions is how to output breadcrumbs before switch blocks but with right content. Maybe I need a buffer or idk?
This is a good example of why it is such a good idea to separate out logic from presentation: you have a nice abstraction for crumb links, but can't use it properly because your other code is outputting as it goes along, rather than working with abstract data.
Obviously, you could throw away your current structure and port both logic and display directly into a new framework, but assuming you want to migrate from where you are now, here's one approach:
Create an object or array that represents the "result" of whatever module is called. Replace all current use of echo or ?> with concatenation to a string called something like $results['generic_output']. This is effectively like buffering your output, and is enough to let you use your existing abstractions like $breadcrumbs at any time. At this stage, your "template" would consist mostly of echo $results['generic_output'], plus the boilerplate header and footer which is probably already gathered in one place.
Start breaking down the output into sections. Particularly look for sections which are similar on multiple pages. For instance, if you have a "sidebar" with different content on each page but similar styling, make a $results['sidebar_content'] with just the content of that sidebar; the boilerplate to lay it out can then go into your template, and you've reduced the amount of code duplication.
Make the data you pass to the template increasingly abstract, with the goal of eventually having no HTML outside of the template(s). For instance, maybe the sidebar is made up of panels; you might start with an array of HTML blocks, one for each panel, but then turn it into an array of objects based on the actual data being displayed (say, a special offer, or the customer's current basket), with a set of templates for handling different kinds of panel. Eventually, it should be theoretically possible to build a plain-text version of your site with no HTML, just by changing the template layer, and none of the original modules.
The final step is to separate decisions about what to show from decisions about what to do. Continuing with my imaginary sidebar, your template could always receive the current basket as a general variable for use somewhere on the page, rather than as "sidebar item 1". This allows you to completely separate the actions that led into a page from the output that eventually results.
I would like to stress that this is not the way to a perfect framework, or the definitive solution to your situation, but it's one way of organising existing code (and existing thinking) in the right direction.
In the above, the "templates" could just be a set of PHP files using ?> or echo to produce the output, or it could be a dedicated templating system such as Smarty or Twig. Indeed, the point of the separation is that you could change your mind on that front later, because the result of the code modules would be an array of data to be displayed, which is just what Smarty or Twig would need as input.
There are some examples out there that implement a main menu with ajax and use the history API to get nice and expressive url's.
For example: http://diveintohtml5.info/examples/history/casey.html
The problem, following the example, is that you need 2 files per dog, one for the ajax content request, and the other for the url including a header, footer and so on - which even if its just a php include, is annoying to maintain becasue there are lots of duplicate files (especially in the case where there are more people editing the website)
Is there not a better way to do this?
I doubt I am understanding you question correctly but here goes how I would handle it
<?
include("assign.inc");
if ($_REQUEST["hide"] != "all"){
include("head.inc");
}
?>
page content <img src="test.jpg">
<?
if ($_REQUEST["hide"] != "all"){
include("foot.inc");
}
?>
So the ajax call would simply have ?hide=all on the url (or as a post)...if you want to only show the image (and not the text) simply add more criteria (modify hide if's)
i'm working on my own way of handling a bilingual site. my method should allow proper search engine indexing and will keep everything on one page without external files.
one function would handle which content to display:
<?
function l($en, $fr){
echo ($_GET['lang'] === 'fr') ? $fr : $en ;
}
?>
then the appropriate text will display according to language in URL (/?lang=en)
<h1><? l('welcome!', 'bienvenue!') ?></h1>
for an image this is my solution:
<img src="<? l('hi-en.png', 'hi-fr.png')?>" width="100" height="20">
can anyone name drawbacks to this method if used? is it unusual to have a single function handle language for pages which would include all language content?
The general idea of using a singleton or global function like your l function is very common. You're definitely on the right track!
Your method does have some drawbacks, though:
If you have the same text or image that appears in numerous places in the code, you need to maintain the translation in every place.
Updating or correcting a translation requires wading through code, which is very difficult for inexperienced coders or non-coders (say, if you have a translator helping you).
If you were ever to add a new language, you would have to modify every source file, which would be excruciating. This may be unlikely, but if it ever happened, you'd be rather cross with yourself.
A more typical solution is to have the translations located in a separate file, either as a simple hash or as a structured data format like XML, and then your l function would just look like l('welcome'); the parameter is a key, and l will look up the correct translation in the given language from the separate file.