django模板静态文件_使用Django模板和静态文件

django模板静态文件

In my getting started with Django tutorial, I showed you how to get a Django site up and running. The templates we rendered were very basic though.

Django入门教程中 ,我向您展示了如何启动和运行Django网站。 不过,我们呈现的模板非常基础。

This is definitely not how you want your site to look like.

绝对不是您希望网站的外观。

How do you get your site to look better? Simple! Add some styling. In this tutorial, I will show you how to add some CSS and JavaScript to your Django templates in order to make them look much better. To do that, you first need to understand the concept of static files in Django.

您如何使网站看起来更好? 简单! 添加一些样式。 在本教程中,我将向您展示如何向Django模板中添加一些CSS和JavaScript,以使其看起来更好。 为此,您首先需要了解Django中静态文件的概念。

设置Django项目 ( Setting up a Django Project )

Let's set up our test Django project. First, create a folder called projects which is where our app will live.

让我们设置我们的测试Django项目。 首先,创建一个名为projects的文件夹,这是我们应用程序所在的文件夹。

mkdir projects && cd projects

Inside projects, let's use virtualenv to create an environment for our app's dependencies.

projects内部,让我们使用virtualenv为应用程序的依赖关系创建环境。

virtualenvenv --python python3

NOTE: If you do not have virtualenv installed, install it using the command pip install virtualenv.

注:如果尚未安装virtualenv ,请使用命令pip install virtualenv

Once that is done, activate the environment by running the activate shell script.

完成后,通过运行激活外壳脚本来激活环境。

source env/bin/activate

If that command works, you should see an (env) prompt on your terminal.

如果该命令有效,则您应该在终端上看到一个(env)提示。

#(env)~/projects
$

Everything look fine? Awesome! Let's now use pip to install Django into our environment.

一切看起来还好吗? 太棒了! 现在让我们使用pipDjango安装到我们的环境中。

#(env)~/projects
$ pip install django

That command should install Django into your environment. As of the time of writing, the Django version is 1.10.4.

该命令应将Django安装到您的环境中。 在撰写本文时,Django版本为1.10.4

We are then going to call the django-admin script to create our Django app. Let's do that like this:

然后,我们将调用django-admin脚本来创建Django应用。 让我们这样做:

#(env)~/projects
$ django-admin startproject djangotemplates

If you check your projects folder structure, you should now have a new folder called djangotemplates created by Django in addition to the earlier env folder we created.

如果检查projects文件夹结构,那么除了我们创建的较早的env文件夹之外,现在还应该有一个由Django创建的名为djangotemplates的新文件夹。

cd into djangotemplates.

cd进入djangotemplates

Your folder structure should now be similar to this:

您的文件夹结构现在应与此类似:

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--manage.py

All done? You are now ready to begin!

全做完了? 您现在就可以开始了!

用于管理静态文件的设置 ( Settings for managing static files )

Static files include stuff like CSS, JavaScript and images that you may want to serve alongside your site. Django is very opinionated about how you should include your static files. In this article, I will show how to go about adding static files to a Django application.

静态文件包括CSS,JavaScript和您可能希望随网站一起提供的图像。 Django对于如何包含静态文件非常有见地。 在本文中,我将展示如何向Django应用程序添加静态文件。

Open the settings.py file inside the inner djangotemplates folder. At the very bottom of the file you should see these lines:

打开settings.py内内部文件djangotemplates文件夹。 在文件的最底部,您应该看到以下几行:

# djangotemplates/djangotemplates/settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

This line tells Django to append static to the base url (in our case localhost:8000) when searching for static files. In Django, you could have a static folder almost anywhere you want. You can even have more than one static folder e.g. one in each app. However, to keep things simple, I will use just one static folder in the root of our project folder. We will create one later. For now, let's add some lines in the settings.py file so that it looks like this.

该行告诉Django在搜索静态文件时将静态附加到基本URL(在我们的示例中为localhost:8000 )。 在Django中,您几乎可以在任何位置拥有一个static文件夹。 您甚至可以拥有多个static文件夹,例如每个应用程序中都有一个。 但是,为了简单起见,我将仅在项目文件夹的根目录中使用一个static文件夹。 稍后我们将创建一个。 现在,让我们在settings.py文件中添加一些行,使其看起来像这样。

# djangotemplates/djangotemplates/settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

# Add these new lines
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

The STATICFILES_DIRS tuple tells Django where to look for static files that are not tied to a particular app. In this case, we just told Django to also look for static files in a folder called static in our root folder, not just in our apps.

STATICFILES_DIRS元组告诉Django在哪里查找未绑定到特定应用程序的静态文件。 在这种情况下,我们只是告诉Django的也找静态文件的文件夹叫static在我们的根文件夹,不只是在我们的应用程序。

Django also provides a mechanism for collecting static files into one place so that they can be served easily. Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT. In our case, we are telling Django that when we run python manage.py collectstatic, gather all static files into a folder called staticfiles in our project root directory. This feature is very handy for serving static files, especially in production settings.

Django还提供了一种将静态文件收集到一个位置的机制,以便可以轻松提供它们。 Django使用collectstatic命令在应用程序中查找所有静态文件,并在您指定的任何位置(即STATIC_ROOT收集它们。 在我们的例子中,我们告诉Django,当我们运行python manage.py collectstatic ,将所有静态文件收集到项目根目录下的一个名为staticfiles的文件夹中。 此功能非常适合提供静态文件,尤其是在生产设置中。

应用设置 ( App setup )

Create a folder called static on the same level as the inner djangotemplates folder and the manage.py file. You should now have this structure:

在与内部djangotemplates文件夹和manage.py文件相同的级别上创建一个名为static的文件夹。 您现在应该具有以下结构:

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--static
--manage.py

Inside this folder is where we will have any custom CSS and JS we choose to write. On that note, let's add two folders inside the static folder to hold our files, one called css and the other called js. Inside css, create a file called main.css. Add a main.js in the js folder as well. Your static folder should now look like this:

在此文件夹中,我们将选择要编写的任何自定义CSS和JS。 关于这一点,让我们在静态文件夹中添加两个文件夹来保存文件,一个名为css ,另一个称为js 。 在css ,创建一个名为main.css的文件。 main.jsjs文件夹中添加一个main.js 您的静态文件夹现在应如下所示:

--static
----css
------main.cs
----js
------main.js

Once that is done, let's create a new Django app called example that we will be working with. Do you remember how to do that? Don't worry, it's quite simple.

完成后,让我们创建一个名为example的新Django应用程序,我们将使用该应用程序。 你还记得怎么做吗? 不用担心,这很简单。

#(env)~/projects/djangotemplates
$ python manage.py startapp example

Once that is done, you should have a folder called example alongside djangotemplates and static. And of course you should still be able to see the manage.py file.

完成后,您应该在djangotemplatesstatic旁边有一个名为example的文件夹。 当然,您仍然应该能够看到manage.py文件。

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--example
--static
--manage.py

We need to tell Django about our new app. Go to the inner djangotemplates folder, open up settings.py and look for INSTALLED_APPS. Add example under the other included apps.

我们需要向Django介绍我们的新应用。 转到内部的djangotemplates文件夹,打开settings.py并查找INSTALLED_APPS 。 在其他随附的应用下添加example

# djangotemplates/djangotemplates/settings.py

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'example', # Add this line
]

Just to recap, we now have the following folder structure:

回顾一下,我们现在具有以下文件夹结构:

djangotemplates
--djangotemplates
----**init**.py
----settings.py
----urls.py
----wsgi.py
--example
----migrations
------**init**.py
----admin.py
----apps.py
----models.py
----tests.py
----views.py
--static
----css
------main.cs
----js
------main.js
--manage.py

网址定义 ( URL definition )

Let's define a URL to go to our new app. Let's edit djangotemplates/djangotemplates/urls.py to effect that.

让我们定义一个URL以转到我们的新应用程序。 让我们编辑djangotemplates/djangotemplates/urls.py来实现这一点。

# djangotemplates/djangotemplates/urls.py

from django.conf.urls import url, include # Add include to the imports here
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('example.urls')) # tell django to read urls.py in example app
]

After that, in the example app folder, create a new file called urls.py and add the following code:

之后,在example应用程序文件夹中,创建一个名为urls.py的新文件,并添加以下代码:

# djangotemplates/example/urls.py

from django.conf.urls import url
from example import views

urlpatterns = [
    url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named
    url(r'^about/$', views.AboutPageView.as_view(), name='about'),
]

The code we have just written tells Django to match the empty route (i.e localhost:8000) to a view called HomePageView and the route /about/ to a view called AboutPageView. Remember, Django views take in HTTP requests and return HTTP responses. In our case, we shall use a TemplateView that returns a Home Page template and another one for the About page. To do this, inside your example app folder, create another folder called templates. Inside the new templates folder, create two new files called index.html and about.html. Your example app folder should now have this structure:

我们刚刚编写的代码告诉Django将空路由(即localhost:8000)匹配到名为HomePageView的视图,将/about/ AboutPageView到名为AboutPageView的视图。 请记住,Django视图接受HTTP请求并返回HTTP响应。 在我们的例子中,我们将使用一个TemplateView返回一个Homepage模板,另一个用于About页面。 为此,请在example应用程序文件夹中,创建另一个名为templates文件夹。 在新templates文件夹内,创建两个名为index.htmlabout.html新文件。 您的example应用程序文件夹现在应具有以下结构:

--example
----migrations
------**init**.py
----templates
------index.html
------about.html
----admin.py
----apps.py
----models.py
----tests.py
----urls.py
----views.py

Inside the index.html, paste the following code:

index.html ,粘贴以下代码:

<!-- djangotemplates/example/templates/index.html-->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Welcome Home</title>
</head>
<body>
  <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  </p>
  <a href="{% url 'home' %}">Go Home</a>
  <a href="{% url 'about' %}">About This Site</a>
</body>
</html>

Add this code to about.html:

将此代码添加到about.html

<!-- djangotemplates/example/templates/about.html-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>About Us</title>
</head>
<body>
  <p>
  We are a group of Django enthusiasts with the following idiosyncrasies:

  <ol>
    <li>We only eat bananas on Saturdays.</li>
    <li>We love making playing football on rainy days.</li>
  </ol>
  </p>
  <a href="{% url 'home' %}">Go Home</a>
  <a href="{% url 'about' %}">About This Site</a>
</body>
</html>

Notice how we are referring to our links for Go Home and About This Site in our templates. We can use Django's automatic URL reverse lookup because we named our URLs in our urls.py. Neat, huh!

注意我们如何在模板中引用Go Home和“ About This Site链接。 我们可以使用Django的自动URL反向查找,因为我们在urls.py命名了URL。 整洁,呵呵!

We shall see the effect of this code in the next section.

我们将在下一部分中看到此代码的效果。

连接视图 ( Wiring up the views )

Let's add the final code to serve up our templates. We need to edit djangotemplates/example/views.py for this.

让我们添加最终代码以提供我们的模板。 djangotemplates/example/views.py我们需要编辑djangotemplates/example/views.py

# djangotemplates/example/views.py
from django.shortcuts import render
from django.views.generic import TemplateView # Import TemplateView

# Add the two views we have been talking about  all this time :)
class HomePageView(TemplateView):
    template_name = "index.html"


class AboutPageView(TemplateView):
    template_name = "about.html"

Now we can run our app. We first need to make Django's default migrations since this is the first time we are running our app.

现在我们可以运行我们的应用程序了。 首先,我们需要进行Django的默认迁移,因为这是我们第一次运行我们的应用程序。

#(env)~/projects/djangotemplates
$ python manage.py migrate

Once that is done, start your server.

完成后,启动服务器。

#(env)~/projects/djangotemplates
$ python manage.py runserver

Open your browser and navigate to http://localhost:8000. You should be able to see our home page.

打开浏览器并导航到http://localhost:8000 。 您应该可以看到我们的主页。

Clicking the links at the bottom should be able to navigate you between the pages. Here is the About page:

单击底部的链接应该可以在页面之间导航。 这是关于页面:

模板继承 ( Template Inheritance )

Let's shift our focus to the templates folder inside the example app folder. At the moment, it contains two templates, index.html and about.html.

让我们将重点转移到example应用程序文件夹内的模板文件夹。 目前,它包含两个模板, index.htmlabout.html

We would like both these templates to have some CSS included. Instead of rewriting the same code in both of them, Django allows us to create a base template which they will both inherit from. This prevents us from having to write a lot of repeated code in our templates when we need to modify anything that is shared.

我们希望这两个模板都包含一些CSS。 Django无需我们在两者中重写相同的代码,而是允许我们创建它们都将继承的基本模板。 当我们需要修改任何共享的内容时,这使我们不必在模板中编写很多重复的代码。

Let's create the base template now. Create a file called base.html in djangotemplates/example/templates. Write this code inside it:

现在创建基本模板。 在djangotemplates/example/templates创建一个名为base.html的文件。 在其中写入以下代码:

<!-- djangotemplates/example/templates/base.html -->

{% load static %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      Django Sample Site - {% block title %}{% endblock %}
    </title>

    <script src="{% static 'js/main.js' %}"></script> <!-- This is how to include a static file -->
    <link rel="stylesheet" href="{% static 'css/main.css' %}" type="text/css" />
  </head>
  <body>
    <div class="container">
      {% block pagecontent %}
      {% endblock %}
    </div>
  </body>
</html>

The very first line in the file, {% load static %}, uses Django's special template tag syntax to tell the template engine to use the files in the static folder in this template.

文件中的第一行{% load static %}使用Django的特殊模板标记语法来告诉模板引擎使用此模板中static文件夹中的文件。

In the title tag, we use a Django block. What this means is that in any Django template which inherits from this base template, any HTML which is inside a block named title will be plugged into the title block. The same goes for the body tag's pagecontent block. If this sounds confusing, don't worry. You will see it in action soon.

在标题标签中,我们使用Django块。 这意味着在从该基本模板继承的任何Django模板中,名为title的块内的任何HTML都将插入到title块中。 body标签的pagecontent块也是如此。 如果这听起来令人困惑,请不要担心。 您很快就会看到它的实际效果。

If you are not running your Django server, run it by executing python manage.py runserver in your terminal. Go to http://localhost:8000. You should see the previous template.

如果您没有运行Django服务器,请在终端中执行python manage.py runserver来运行它。 转到http:// localhost:8000 。 您应该看到先前的模板。

Now edit the index.html template to inherit from the base template.

现在,编辑index.html模板以从基本模板继承。

<!-- djangotemplates/example/templates/index.html -->

{% extends 'base.html' %} <!-- Add this for inheritance -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Welcome Home</title>
</head>
<body>
    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
      Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </p>
    <a href="{% url 'home' %}">Go Home</a>
    <a href="{% url 'about' %}">About This Site</a>
</body>
</html>

Reload the page in your browser. Nothing appears! This is because Django expects your content to be written inside the blocks we defined in the base template so that they can be rendered. Edit the index.html to add the blocks:

在浏览器中重新加载页面。 什么都没出现! 这是因为Django希望您的内容写在我们在基本模板中定义的块内,以便可以呈现它们。 编辑index.html以添加块:

<!-- djangotemplates/example/templates/index.html -->

{% extends 'base.html' %}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{% block title %}Welcome Home {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
      Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </p>
    <a href="{% url 'home' %}">Go Home</a>
    <a href="{% url 'about' %}">About This Site</a>
  {% endblock %}
</body>
</html>

Reload the page in the browser and voila! Your content should appear again!

在浏览器中重新加载页面,瞧! 您的内容应该再次出现!

We can also edit the about.html template to use the same.

我们还可以编辑about.html模板以使用相同的模板。

<!-- djangotemplates/example/templates/about.html -->

{% extends 'base.html' %} <!-- Add this for inheritance -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}About Us {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>
    We are a group of Django enthusiasts with the following idiosyncrasies:

    <ol>
        <li>We only eat bananas on Saturdays.</li>
        <li>We love making playing football on rainy days.</li>
    </ol>
    </p>
    <a href="{% url 'home' %}">Go Home</a>
    <a href="{% url 'about' %}">About This Site</a>
  {% endblock %}
</body>
</html>

You should now see this on the About page:

现在,您应该在“关于”页面上看到以下内容:

Which is exactly the same as before!

与以前完全一样!

However, now since both templates inherit from a base template, I can easily style them. Open up main.css in your css folder and add these styles:

但是,由于这两个模板都继承自基本模板,因此我可以轻松对其进行样式设置。 在您的css文件夹中打开main.css并添加以下样式:

.container {
    background: #eac656;
    margin: 10 10 10 10;
    border: 3px solid black;
}

This will style the container div which we are loading our content into. Refresh your browser. You should see this:

这将为我们将内容加载到的容器div设置样式。 刷新浏览器。 您应该看到以下内容:

The Home Page:

主页:

The About Page:

关于页面:

使用视图数据渲染模板 ( Rendering templates with data from views )

You can use Django's template engine to display data in very powerful ways. In this section, I will create a Django view that will pass data into a template. I will then show you how to access that data in the template and display it to the user.

您可以使用Django的模板引擎以非常强大的方式显示数据。 在本节中,我将创建一个Django视图,该视图会将数据传递到模板中。 然后,我将向您展示如何访问模板中的数据并将其显示给用户。

First things first, open up views.py in the example app folder. We will add a new view to serve data into our yet to exist data.html template. Modify the views.py file to look like this:

首先,请在example应用程序文件夹中打开views.py 。 我们将添加一个新视图以将数据提供到我们尚不存在的data.html模板中。 修改views.py文件,使其如下所示:

# djangotemplates/example/views.py

from django.shortcuts import render
from django.views.generic import TemplateView

class HomePageView(TemplateView):
    template_name = "index.html"

class AboutPageView(TemplateView):
    template_name = "about.html"

# Add this view
class DataPageView(TemplateView):
    def get(self, request, **kwargs):
        # we will pass this context object into the
        # template so that we can access the data
        # list in the template
        context = {
            'data': [
                {
                    'name': 'Celeb 1',
                    'worth': '3567892'
                },
                {
                    'name': 'Celeb 2',
                    'worth': '23000000'
                },
                {
                    'name': 'Celeb 3',
                    'worth': '1000007'
                },
                {
                    'name': 'Celeb 4',
                    'worth': '456789'
                },
                {
                    'name': 'Celeb 5',
                    'worth': '7890000'
                },
                {
                    'name': 'Celeb 6',
                    'worth': '12000456'
                },
                {
                    'name': 'Celeb 7',
                    'worth': '896000'
                },
                {
                    'name': 'Celeb 8',
                    'worth': '670000'
                }
            ]
        }

        return render(request, 'data.html', context)

We are using the same kind of view we used to render the other templates. However, we are now passing a context object to the render method. The key-value pairs defined in the context will be available in the template being rendered and we can iterate through them just like any other list.

我们正在使用与呈现其他模板相同的视图。 但是,我们现在将context对象传递给render方法。 在上下文中定义的键值对将在呈现的模板中可用,我们可以像其他任何列表一样遍历它们。

To finish this up, go to the urls.py file in the howdy app and add the URL pattern for our new view so that it looks like this:

要完成此操作,请转到howdy应用程序中的urls.py文件,并为我们的新视图添加URL模式,如下所示:

# djangotemplates/example/urls.py

from django.conf.urls import url
from example import views

urlpatterns = [
    url(r'^$', views.HomePageView.as_view(), name='home'),
    url(r'^about/$', views.AboutPageView.as_view(), name='about'),
    url(r'^data/$', views.DataPageView.as_view(), name='data'),  # Add this URL pattern
]

Finally, let's create the template. In the templates folder, create a file called data.html and write this code inside it.

最后,让我们创建模板。 在templates文件夹中,创建一个名为data.html文件,并将此代码写入其中。

<!-- djangotemplates/example/templates/data.html -->

{% extends 'base.html' %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% block pagecontent %}
    <div class="table-div">
    <!-- We will display our data in a normal HTML table using Django's
    template for-loop to generate our table rows for us-->
      <table class="table">
        <thead>
          <tr>
            <th>Celebrity Name</th>
            <th>Net Worth</th>
          </tr>
        </thead>
        <tbody>
          {% for celebrity in data %}
            <tr>
              <td>{{ celebrity.name }}</td>
              <td>{{ celebrity.worth }}</td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% endblock %}
  </body>
</html>

In data.html, you can see that we use what is essentially a for loop to go through the data list. Binding of values in Django templates is done using {{}} curly brackets much like in AngularJS.

data.html ,您可以看到我们实际上使用了for循环来遍历数据列表。 Django模板中值的绑定是使用{{}}大括号完成的,就像AngularJS中一样。

With your server running, go to http://localhost:8000/data/ to see the template.

在服务器运行的情况下,转到http://localhost:8000/data/以查看模板。

将摘要包含到模板中 ( Including snippets into your templates )

We now have three templates, index.html, about.html and data.html. Let's link them together using a simple navigation bar. First up, let's write the code for the navigation bar in another HTML template.

现在,我们有了三个模板, index.htmlabout.htmldata.html 。 让我们使用一个简单的导航栏将它们链接在一起。 首先,让我们在另一个HTML模板中编写导航栏的代码。

In the templates folder inside the example app, create a new folder called partials. Inside it, create a file called nav-bar.html. The templates folder structure should now be like this:

example应用程序内的templates文件夹中,创建一个名为partials的新文件夹。 在其中创建一个名为nav-bar.html 。 template文件夹结构现在应如下所示:

templates
----index.html
----about.html
----data.html
----partials
------nav-bar.html

Edit the nav-bar.html partial so that it contains this code:

编辑nav-bar.html部分,使其包含以下代码:

<!-- djangotemplates/example/templates/partials/nav-bar.html -->

<div class="nav">
  <a href="{% url 'home' %}">Go Home</a>
  <a href="{% url 'about' %}">About This Site</a>
  <a href="{% url 'data' %}">View Data</a>
</div>

Including snippets in a template is very simple. We use the includes keyword provided by Django's templating engine. Go ahead and modify index.html to this:

在模板中包含摘要非常简单。 我们使用Django的模板引擎提供的includes关键字。 继续并将index.html修改为:

<!-- djangotemplates/example/templates/index.html -->

{% extends 'base.html' %}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{% block title %}Welcome Home {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
      Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </p>
    {% include 'partials/nav-bar.html' %} <!--Add this-->

    <!-- Remove these two lines -- >
    <!-- <a href="{% url 'home' %}">Go Home</a> -->
    <!-- <a href="{% url 'about' %}">About This Site</a> -->
  {% endblock %}
</body>
</html>

Modify about.html to this:

修改about.html为此:

<!-- djangotemplates/example/templates/about.html -->

{% extends 'base.html' %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}About Us {% endblock %}</title>
</head>
<body>
  {% block pagecontent %}
    <p>
    We are a group of Django enthusiasts with the following idiosyncrasies:

    <ol>
        <li>We only eat bananas on Saturdays.</li>
        <li>We love making playing football on rainy days.</li>
    </ol>
    </p>
    {% include 'partials/nav-bar.html' %} <!--Add this-->

    <!-- Remove these two lines -- >
    <!-- <a href="{% url 'home' %}">Go Home</a> -->
    <!-- <a href="{% url 'about' %}">About This Site</a> -->
  {% endblock %}
</body>
</html>

Lastly, modify data.html to this:

最后,将data.html修改为:

<!-- djangotemplates/example/templates/data.html -->

{% extends 'base.html' %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% block pagecontent %}
    <div class="table-div">
      <table class="table">
        <thead>
          <tr>
            <th>Celebrity Name</th>
            <th>Net Worth</th>
          </tr>
        </thead>
        <tbody>
          {% for celebrity in data %}
            <tr>
              <td>{{ celebrity.name }}</td>
              <td>{{ celebrity.worth }}</td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% include 'partials/nav-bar.html' %} <!--Add this-->
    {% endblock %}
  </body>
</html>

Time to check out our work! Open your browser and navigate to http://localhost:8000. You should see this:

是时候检查我们的工作了! 打开浏览器并导航到http://localhost:8000 。 您应该看到以下内容:

All the pages are now linked with the navbar so you can easily navigate back and forth through them, all with minimal code written. Here is the data.html template:

现在,所有页面都与导航栏链接,因此您可以轻松地在它们之间来回导航,而只需编写最少的代码即可。 这是data.html模板:

And here is about.html:

这是about.html

Note: I have added the following CSS to syle the links in the navbar. Feel free to use it or play with your own styles:

注意:我添加了以下CSS,以在导航栏中显示链接的样式。 随意使用它或以自己的风格玩:

// djangtotemplates/static/css/main.css

.container {
    background: #eac656;
    margin: 10 10 10 10;
    border: 3px solid black;
}

.nav a {
    background: #dedede;
}

筛选器 ( Filters )

Filters take data piped to them and output it in a formatted way. Django templates have access to the humanize collection of filters, which make data more human readable. Let's make the celebrity's networth field in the data template more readable by using some of these filters.

筛选器接收通过管道传递给它们的数据,并以格式化的方式将其输出。 Django模板可以访问humanize的过滤器集合,从而使数据更易于阅读。 通过使用其中一些过滤器,让数据模板中的名人的networth字段更具可读性。

To use Django's humanize filters, you first need to edit some settings. Open up djangotemplates/settings.py and edit the INSTALLED_APPS list to this:

要使用Django的人性化过滤器,您首先需要编辑一些设置。 打开djangotemplates/settings.py并将INSTALLED_APPS列表编辑为此:

# djangotemplates/djangotemplates/settings.py

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize', # Add this line. Don't forget the trailing comma
    'example',
]

We can now use a filter in our templates. We are going to use the intcomma filter to add comma's in large numbers to make them easier to read. Let's modify data.html to this:

现在,我们可以在模板中使用过滤器。 我们将使用intcomma过滤器添加大量的逗号,以使其更易于阅读。 让我们将data.html修改为:

<!-- djangotemplates/example/templates/data.html -->

{% extends 'base.html' %}
{% load humanize %} <!-- Add this-->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {% block pagecontent %}
    <div class="table-div">
      <table class="table">
        <thead>
          <tr>
            <th>Celebrity Name</th>
            <th>Net Worth</th>
          </tr>
        </thead>
        <tbody>
          {% for celebrity in data %}
            <tr>
              <td>{{ celebrity.name }}</td>
              <td>$ {{ celebrity.worth | intcomma }}</td> <!--Modify this line-->
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
    {% include 'partials/nav-bar.html' %}
    {% endblock %}
  </body>
</html>

When you go to http://localhost:8000/data/, you should now have a more friendly list of net worth values:

当您转到http://localhost:8000/data/ ,现在应该有了一个更友好的净值列表:

There are many more filters included in the humanize package. Read about them here

humanize软件包中包含更多的过滤器。 在这里了解他们

收集静态文件 ( Collecting Static Files )

Remember we talked about collecting static files? Try the following command:

还记得我们谈论过收集静态文件吗? 尝试以下命令:

python manage.py collectstatic

You should see a prompt like the following:

您应该看到如下提示:

You have requested to collect static files at the destination
location as specifiedin your settings:

      /Users/amos/projects/djangotemplates/staticfiles

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel:

Go ahead and say yes.

继续说yes

This command will tell Django to go through all your project folders, look for all static files and store them in one place (the static root we defined in the settings). This is very efficient especially if you are deploying your site to production.

该命令将告诉Django浏览所有项目文件夹,查找所有静态文件并将它们存储在一个位置(我们在设置中定义的静态根目录)。 这非常有效,尤其是在将站点部署到生产环境中时。

When you run the command collectstatic, you should see a new folder called staticfiles created in the root of your project folder. You can change this location to something else by editing the static root setting in your project's settings.py file. To use these staticfiles, in your templates you will say load staticfiles instead of load static. Everything else is the same as with using the previous static folder.

当运行命令collectstatic ,您应该在项目文件夹的根目录中看到一个名为staticfiles的新文件夹。 您可以通过在项目的settings.py文件中编辑静态根设置来将此位置更改为其他位置。 要使用这些staticfiles ,在您的模板中将说是load static load staticfiles而不是load static 。 其他所有操作与使用先前的static文件夹相同。

结论 ( Conclusion )

Congratulations on reaching the end of this tutorial! By now you should have a more detailed understanding of how Django templates work. If you need deeper information, remember the docs are your friend. You can find the full code for this tutorial here. Make sure to leave any thoughts, questions or concerns in the comments below.

恭喜您本教程结束! 到目前为止,您应该对Django模板的工作方式有更详细的了解。 如果您需要更深入的信息,请记住文档是您的朋友。 您可以在此处找到本教程的完整代码。 确保在下面的评论中留下任何想法,问题或疑虑。

翻译自: https://scotch.io/tutorials/working-with-django-templates-static-files

django模板静态文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值