2010-04-07 9 views
15

creo que este guión es de gran interés para cualquier novato por aquí :) :) incluido yoruta de navegación dinámico simple

Lo que quiero es crear un poco de código que pueda utilizar en cualquier archivo y generará una miga de pan de esta manera:

Si el archivo se llama "website.com/templates/index.php" la ruta de exploración debe mostrar:

Website.com > Templates 

  ^^ enlace                                         ^^ texto plano

Si el archivo se llama "website.com/templates/template_some_name.php" la ruta de exploración debe mostrar:

Website.com > Templates > Template Some Name 

  ^^ enlace                                       ^^ enlace                                 ^^ texto plano

+0

¿Alguien sabe cómo hacer esto en Twig? Consulte mi pregunta aquí: http://stackoverflow.com/questions/38551401/how-to-create-a-dynamic-breadcrumb-nav-in-twig – user3464091

Respuesta

23

Hmm, de los ejemplos que le dio parece "$ _SERVER ['REQUEST_URI']" y la función explode() podría ayudarlo. Puede usar la explosión para dividir la URL que sigue al nombre de dominio en una matriz, separándola en cada barra diagonal.

Como un ejemplo muy básico, algo como esto podrían ser implementadas:

$crumbs = explode("/",$_SERVER["REQUEST_URI"]); 
foreach($crumbs as $crumb){ 
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' '); 
} 
+0

¡Gracias por el código! –

3

uso parse_url y entonces la salida el resultado en un bucle:

$urlinfo = parse_url($the_url); 
echo makelink($urlinfo['hostname']); 
foreach($breadcrumb in $urlinfo['path']) { 
    echo makelink($breadcrumb); 
} 

function makelink($str) { 
    return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>'; 
} 

(pseudocódigo)

+0

¡Gracias por el código! –

39

Este puede ser excesivo para una simple ruta de exploración, pero vale la pena intentarlo. Recuerdo haber tenido este problema hace mucho tiempo cuando comencé, pero nunca lo resolví realmente. Es decir, hasta que decidí escribir esto ahora. :)

He documentado lo mejor que puedo en línea, en la parte inferior hay 3 posibles casos de uso. ¡Disfrutar!(No dude en hacer cualquier pregunta que pueda tener)

<?php 

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path 
function breadcrumbs($separator = ' &raquo; ', $home = 'Home') { 
    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values 
    $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))); 

    // This will build our "base URL" ... Also accounts for HTTPS :) 
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'; 

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL) 
    $breadcrumbs = Array("<a href=\"$base\">$home</a>"); 

    // Find out the index for the last value in our path array 
    $last = end(array_keys($path)); 

    // Build the rest of the breadcrumbs 
    foreach ($path AS $x => $crumb) { 
     // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space) 
     $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb)); 

     // If we are not on the last index, then display an <a> tag 
     if ($x != $last) 
      $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>"; 
     // Otherwise, just display the title (minus) 
     else 
      $breadcrumbs[] = $title; 
    } 

    // Build our temporary array (pieces of bread) into one big string :) 
    return implode($separator, $breadcrumbs); 
} 

?> 

<p><?= breadcrumbs() ?></p> 
<p><?= breadcrumbs(' > ') ?></p> 
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p> 
+0

¡Gracias por el código! –

+0

No hay problema, espero que ayude :) –

+7

+1 A veces, la respuesta elegida no se ajusta a todas las situaciones. – dpp

2

bueno Dominic su respuesta era agradable, pero si dispone de un sitio como http://localhost/project/index.php el enlace 'proyecto' se repite, ya que es parte de la base de $ y también aparece en el $ path array. Así que modifiqué y eliminé el primer elemento de la matriz $ path.

//Trying to remove the first item in the array path so it doesn't repeat 
array_shift($path); 

No sé si es la manera más elegante, pero ahora me funciona.

agrego que el código antes de éste en la línea 13 o algo

// Find out the index for the last value in our path array 
$last = end(array_keys($path)); 
6

también hizo un pequeño script usando RDFa (también se puede utilizar microdatos u otros formatos) Check it out on google Este script también tiene en cuenta su sitio estructura.

function breadcrumbs($text = 'You are here: ', $sep = ' &raquo; ', $home = 'Home') { 
//Use RDFa breadcrumb, can also be used for microformats etc. 
$bc  = '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text; 
//Get the website: 
$site = 'http://'.$_SERVER['HTTP_HOST']; 
//Get all vars en skip the empty ones 
$crumbs = array_filter(explode("/",$_SERVER["REQUEST_URI"])); 
//Create the home breadcrumb 
$bc .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>'; 
//Count all not empty breadcrumbs 
$nm  = count($crumbs); 
$i  = 1; 
//Loop the crumbs 
foreach($crumbs as $crumb){ 
    //Make the link look nice 
    $link = ucfirst(str_replace(array(".php","-","_"), array(""," "," ") ,$crumb)); 
    //Loose the last seperator 
    $sep  = $i==$nm?'':$sep; 
    //Add crumbs to the root 
    $site .= '/'.$crumb; 
    //Make the next crumb 
    $bc  .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>'; 
    $i++; 
} 
$bc .= '</div>'; 
//Return the result 
return $bc;} 
3

empecé con el código de Dominic Barnes, que se incorpora la retroalimentación de cWoDeR y todavía tenía problemas con los enlaces al tercer nivel cuando utilicé un subdirectorio. Así que lo reescribí y he incluido el código a continuación.

Tenga en cuenta que he levantado mi estructura del sitio web de tal manera que las páginas estén subordinadas a (vinculado a) una página en el nivel raíz están configurados de la siguiente manera:

  • Crear una carpeta con el EXACTA mismo nombre que el archivo (incluyendo capitalización), menos el sufijo, como una carpeta en el nivel raíz

  • lugar todos los archivos/páginas subordinadas a esta carpeta

(por ejemplo, si quieren páginas subalterno para clientes.php:

  • crear una carpeta llamada clientes al mismo nivel que clientes.php

  • añadir un archivo index.php en la carpeta Clientes que redirige a la página de llamadas para la carpeta (ver abajo el código)

Esta estructura funcionará para múltiples niveles de subcarpetas.

Simplemente asegúrese de seguir la estructura de archivos descrita anteriormente E inserte un archivo index.php con el código que se muestra en cada subcarpeta.

El código en la página index.php en cada subcarpeta se parece a:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>Redirected</title> 
</head> 
<body> 
<?php 
$root_dir = "web_root/" ; 
$last_dir=array_slice(array_filter(explode('/',$_SERVER['PHP_SELF'])),-2,1,false) ; 
$path_to_redirect = "/".$root_dir.$last_dir[0].".php" ; 
header('Location: '.$path_to_redirect) ; 
?> 
</body> 
</html> 

Si utiliza el directorio raíz del servidor como su raíz web (es decir,/var/www/html) a continuación, establezca $ root_dir = "": (NO deje el final "/" en).Si utiliza un subdirectorio para su sitio web (es decir,/var/www/html/web_root, configure $ root_dir = "raíz_web /"; (reemplace web_root con el nombre real de su directorio web) (asegúrese de incluir el final /)

en todo caso, aquí está mi (derivado) código:

<?php 

// Big Thank You to the folks on StackOverflow 
// See http://stackoverflow.com/questions/2594211/php-simple-dynamic-breadcrumb 
// Edited to enable using subdirectories to /var/www/html as root 
// eg, using /var/www/html/<this folder> as the root directory for this web site 
// To enable this, enter the name of the subdirectory being used as web root 
// in the $directory2 variable below 
// Make sure to include the trailing "/" at the end of the directory name 
// eg use  $directory2="this_folder/" ; 
// do NOT use $directory2="this_folder" ; 
// If you actually ARE using /var/www/html as the root directory, 
// just set $directory2 = "" (blank) 
// with NO trailing "/" 

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path 
function breadcrumbs($separator = ' &raquo; ' , $home = 'Home') 
{ 

    // This sets the subdirectory as web_root (If you want to use a subdirectory) 
    // If you do not use a web_root subdirectory, set $directory2=""; (NO trailing /) 
    $directory2 = "web_root/" ; 

    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values 
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ; 
    $path_array = array_filter(explode('/',$path)) ; 

    // This line of code accommodates using a subfolder (/var/www/html/<this folder>) as root 
    // This removes the first item in the array path so it doesn't repeat 
    if ($directory2 != "") 
    { 
    array_shift($path_array) ; 
    } 

    // This will build our "base URL" ... Also accounts for HTTPS :) 
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'. $directory2 ; 

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL) 
    $breadcrumbs = Array("<a href=\"$base\">$home</a>") ; 

    // Get the index for the last value in our path array 
    $last = end($path_array) ; 

    // Initialize the counter 
    $crumb_counter = 2 ; 

    // Build the rest of the breadcrumbs 
    foreach ($path_array as $crumb) 
    { 
     // Our "title" is the text that will be displayed representing the filename without the .suffix 
     // If there is no "." in the crumb, it is a directory 
     if (strpos($crumb,".") == false) 
     { 
      $title = $crumb ; 
     } 
     else 
     { 
      $title = substr($crumb,0,strpos($crumb,".")) ; 
     } 

     // If we are not on the last index, then create a hyperlink 
     if ($crumb != $last) 
     { 
      $calling_page_array = array_slice(array_values(array_filter(explode('/',$path))),0,$crumb_counter,false) ; 
      $calling_page_path = "/".implode('/',$calling_page_array).".php" ; 
      $breadcrumbs[] = "<a href=".$calling_page_path.">".$title."</a>" ; 
     } 

     // Otherwise, just display the title 
     else 
     { 
      $breadcrumbs[] = $title ; 
     } 

     $crumb_counter = $crumb_counter + 1 ; 

    } 
    // Build our temporary array (pieces of bread) into one big string :) 
    return implode($separator, $breadcrumbs) ; 
} 

// <p><?= breadcrumbs() ? ></p> 
// <p><?= breadcrumbs(' > ') ? ></p> 
// <p><?= breadcrumbs(' ^^ ', 'Index') ? ></p> 
?> 
2

aquí es una gran ruta de navegación dinámica sencilla (ajustar según sea necesario):

<?php 
    $docroot = "/zen/index5.php"; 
    $path =($_SERVER['REQUEST_URI']); 
    $names = explode("/", $path); 
    $trimnames = array_slice($names, 1, -1); 
    $length = count($trimnames)-1; 
    $fixme = array(".php","-","myname"); 
    $fixes = array(""," ","My<strong>Name</strong>"); 
    echo '<div id="breadwrap"><ol id="breadcrumb">'; 
    $url = ""; 
    for ($i = 0; $i <= $length;$i++){ 
    $url .= $trimnames[$i]."/"; 
     if($i>0 && $i!=$length){ 
      echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>'; 
    } 
    elseif ($i == $length){ 
     echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';  
    } 
    else{ 
     echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span>&nbsp;</span></a></li>'; 
    } 
} 
echo '</ol>'; 
?> 
0

uno mejor usando explode() función es como sigue ...

No olvide reemplazar su variable URL en el hipervínculo href.

<?php 
    if($url != ''){ 
     $b = ''; 
     $links = explode('/',rtrim($url,'/')); 
     foreach($links as $l){ 
      $b .= $l; 
      if($url == $b){ 
       echo $l; 
      }else{ 
       echo "<a href='URL?url=".$b."'>".$l."/</a>"; 
      } 
      $b .= '/'; 
     } 
    } 
?> 
Cuestiones relacionadas