duanhui5344 2016-01-27 17:59
浏览 68
已采纳

Silm路由php

I have created a database in mySql and have a page for portfolio items. However when I try to create a link to an item of the portfolio via the id I keep getting errors.

I have had a look at the slim docs

I have also had a look at various questions already here on stackoverflow, including;

This question

There were a few more I viewed about group routing, but am still getting confused. I have read on the internet about using PDO for it, but have not covered that yet. I am wandering if there is a way to route a portfolio item when clicked on to a template, where the url will use the id number of the row in the mysql table?

Here is my index file, if you need to see more please let me know. Many thanks

<?php

require __DIR__ . '/vendor/autoload.php';
date_default_timezone_set ( "Europe/London" );


$app = new \Slim\Slim( array(
  'view' => new \Slim\Views\Twig()
));


$view = $app->view();
$view->parserOptions = array(
    'debug' => true,

);

$view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

$dbc = mysqli_connect('localhost','root','pass','tom_db')
or die('Error Connecting to mysql server');

$query = "SELECT id  FROM documentaries";
$result = mysqli_query($dbc,$query);

while ($row = mysqli_fetch_assoc($result)){
        $data[] = $row["id"];
}



//what happens here is what will run with our object
$app->get('/', function() use($app){
  $app->render('about.twig');
});


//portfolio page
    $app->get('/portfolio', function() use ($app) {
        $app->render('portfolio.twig');
    });

    $app->get('portfolio/{id}', function ($id) {
        $app->render('portfolioitem.twig', array(
            'data' => $data
        ));
    });

$app->get('/contact', function() use($app){
  $app->render('contact.twig');
})->name('contact');

$app->run();


?>

EDIT/UPDATE:

The error I am having is that when clicking on a portfolio link it does not render the url portfolio/1 however if I manually enter the url in to the browser it renders the html with no styles. I am rendering a twig file, but it does not seem to be working

Here is my updated index file;

<?php

require __DIR__ . '/vendor/autoload.php';
date_default_timezone_set ( "Europe/London" );

\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();

$app = new \Slim\Slim( array(
  'view' => new \Slim\Views\Twig()
));


$view = $app->view();
$view->parserOptions = array(
    'debug' => true,

);

$view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

//what happens here is what will run with our object
$app->get('/', function() use($app){
  $app->render('about.twig');
});

//portfolio page
$app->get('/portfolio', function() use($app){
  $app->render('portfolio.twig');
})->name('portfolio');

//this is function where the problem is, when in the portfolio.twig file it does not link to this
$app->get('/portfolio/:id', function ($id) use ($app) {
    // include out mysql connection code and make the connection
    $db = mysqli_connect('localhost', 'root', 'pass', 'tom_db');


    // query the database
    $rs = mysqli_query($db, "SELECT id FROM documentaries WHERE id=$id" );

    // convert the record set into an associative array so we can work with it easily
    $data = mysqli_fetch_assoc($rs);


    $app->render('portfolioitem.twig', array(
            'data' => $data
        )
    );
});


$app->get('/contact', function() use($app){
  $app->render('contact.twig');
})->name('contact');

$app->run();


?>

Edit: additional twig files added

This is my portfolioitem.twig

{% extends 'main.twig' %}

{% block nav %}
     <ul>
        <li><a href="{{ baseUrl() }}" >About</a></li>
        <li><a href="{{ siteUrl('/portfolio') }}" class="selected">Portfolio</a></li>
        <li><a href="{{ siteUrl('/clients') }}">Clients</a></li>
        <li><a href="{{ siteUrl('/teaching') }}">Teaching</a></li>
        <li><a href="{{ siteUrl('/contact') }}">Contact</a></li>
     </ul>
 {% endblock nav %}
{% block content %}

  <section>
    <h2>This is a test</h2>
  </section>

{% endblock content %}

This is my portfolio.twig

{% extends 'main.twig' %}

{% block nav %}
     <ul>
        <li><a href="{{ baseUrl() }}" >About</a></li>
        <li><a href="{{ siteUrl('/portfolio') }}" class="selected">Portfolio</a></li>
        <li><a href="{{ siteUrl('/clients') }}">Clients</a></li>
        <li><a href="{{ siteUrl('/teaching') }}">Teaching</a></li>
        <li><a href="{{ siteUrl('/contact') }}">Contact</a></li>
     </ul>
 {% endblock nav %}

{% block content %}

      <section>
        <div class="showreel-container">
         <iframe src="https://player.vimeo.com/video/148640837?title=0&byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
        </div>
      </section>

      <section>

        <div id="controls" id="Controls">

            <button class="filter" data-filter="all">All</button>
            <button class="filter" data-filter=".documentaries">Documentary</button>
            <button class="filter" data-filter=".commercial">Commercial</button>
            <button class="filter" data-filter=".charity">Charity/NGO/Commisions</button>
            <button class="filter" data-filter=".music">Music</button>
            <button class="filter" data-filter=".drama">Drama</button>

        </div>



        <div id="Container" class="container">

          <div class="mix documentaries" data-myorder="1"><a href="portfolio/{{ data.id }}"><img src="img/numbers-01" alt="Image one"/></a></div>
          <div class="mix commercial" data-myorder="2"><a href=""><img src="img/numbers-02" alt="Image two"/></a></div>
          <div class="mix commerical" data-myorder="3"><a href=""><img src="img/numbers-06" alt="Image six"/></a></div>
          <div class="mix charity" data-myorder="4"><a href=""><img src="img/numbers-09" alt="Image nine"/></a></div>
          <div class="mix music" data-myorder="5"><a href=""><img src="img/numbers-12" alt="Image twelve"/></a></div>
          <div class="mix drama" data-myorder="6"><a href=""><img src="img/numbers-01" alt="Image one"/></a></div>
          <div class="mix music" data-myorder="5"><a href=""><img src="img/numbers-12" alt="Image twelve"/></a></div>
          <div class="mix charity" data-myorder="5"><a href=""><img src="img/numbers-12" alt="Image twelve"/></a></div>

          <div class="gap"></div>
          <div class="gap"></div>

        </div>


      </section>

{% endblock content %}

Finally this is my main.twig file;

<!DOCTYPE html>
<html>
  <head>
    {% block head %}
      <meta charset="utf-8">
      <title>Tom Turner - Director of Photography</title>
      <link rel="stylesheet" href="css/normalize.css">
      <link href='https://fonts.googleapis.com/css?family=Changa+One|Open+Sans:400,400italic,700,700italic,800' rel='stylesheet' type='text/css'>
      <link rel="stylesheet" href="css/main.css">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      <script type="text/javascript" src="js/jquery.mixitup.min.js"></script>
      <script type="text/javascript" src="js/main.js"></script>
      <script type="text/javascript" src="js/responsivemenu.js"></script>

    {% endblock head %}
  </head>

  <body>
    <header>
      <a href="index.html" id="logo">
        <h1>Tom Turner</h1>
        <h2>Director of Photography</h2>
      </a>
      <nav>
        {% block nav %}
          <ul>
            <li><a href="{{ baseUrl() }}" class="selected">About</a></li>
            <li><a href="{{ siteUrl('/portfolio') }}">Portfolio</a></li>
            <li><a href="{{ siteUrl('/clients') }}">Clients</a></li>
            <li><a href="{{ siteUrl('/teaching') }}">Teaching</a></li>
            <li><a href="{{ siteUrl('/contact') }}">Contact</a></li>
          </ul>
        {% endblock nav %}
      </nav>
    </header>

    <div id="wrapper">

      {% block content %}
      {% endblock content %}

    </div>

     <footer class="main-footer">
       {% block footer %}


        <div id="footer-notes">
          <p>Tom Turner - Director of Photography</p>
          <p>&copy; Tom Turner - All Rights Reserved</p>
        </div>
       <div id="mayur">
          <p>&copy; 2015 Website by <a href="https//:www.mayurpande.com">Mayur Pande</a></p>

        </div>

        <div class="social-media">
          <ul>

              <li><a href="mailto:tom@allritesreversed.co.uk"><img src="img/mail_circle.png" alt="Email Logo" /></a></li>
              <li><a href="https://www.facebook.com/tom.turner.397501?fref=ts"><img src="img/fbcircle.png" alt="Facebook Logo" /></a></li>
              <li><a href="https://vimeo.com/user6107855"><img src="img/vimeo_circle.png" alt="Vimeo Logo" /></a></li>
              <li><a href="https://twitter.com/intent/tweet?screen_name=mayurpandeuk"><img src="img/twitter_circle.png" alt="Twitter Logo" /></a></li>

            </ul>
          </div>
       {% endblock footer %}
      </footer>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
      <script type="text/javascript" src="js/jquery.mixitup.min.js"></script>
      <script type="text/javascript" src="js/main.js"></script>
      <script type="text/javascript" src="js/responsivemenu.js"></script>

  </body>
</html>

my htaccess file;

RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
  • 写回答

1条回答 默认 最新

  • dongluedeng1524 2016-01-29 12:18
    关注

    Your stylesheets are relative to the current URL path, so when you are at

    /portfolio, it will look for /portfolio/main.css. Update your link elements to include the site URL, or make them relative to the root, by using /main.css (note the / at the beginning).

    The same applies to the links in your templates, portfolio/{{ data.id }} will try to point to /portfolio/portfolio/{{ data.id }}, again, add the site url to the beginning, or add the slash.

    If you are using Slim V3, consider using https://github.com/slimphp/Twig-View
    Alternatively for V2, use https://github.com/slimphp/Slim-Views, edit: just noticed that you are already using this.

    It allows you to name your routes, e.g:

    $app->get('/portfolio/:id', function ($id) use ($app) {
        ...
    
        $app->render('portfolioitem.twig', array(
                'data' => $data
            )
        );
    })->name('portfolio.id');
    

    And then reference the urls in your template with

    {{ urlFor('portfolio.id', {"id": 17 }) }}
    

    This means that if ever your URLs change, all links referencing it are automatically updated at the same time.

    You will also need to make sure that your .htaccess file is configured correctly. As shown in the Slim documentation at http://docs.slimframework.com/routing/rewrite/, it should contain

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    

    Issue 2

    You are running your query which results an array of results in $data, however you are trying to access the first result using {{ data.id }}, first, you need to loop over the data using

    {% for item in data %}, then you will be able to use {{ item.id }}. Alternatively, get the first item from your PHP like $data = $data[0], and then pass that into your template.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化