Название страницы

Assets: CSS & JavaScript

It looks like your browser may not support the H264 codec. If you’re using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let’s us get back to making more videos :). But as always, please feel free to message us.

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

Even astronauts — who generally spend their time staring into the black absyss — demand a site that is less ugly than this! Let’s fix that!

If you download the course code from the page that you’re watching this video on right now, inside the zip file, you’ll find a start/ directory. And inside that, you’ll see the same tutorial/ directory that I have here. And inside that. I’ve created a new base.html.twig . Copy that and overwrite our version in templates/ :

On a technical level, this is basically the same as before: it has the same blocks: title stylesheets , body and javascripts at the bottom. But now, we have a nice HTML layout that’s styled with Bootstrap.

If you refresh, it should look better. Woh! No change! Weird! Actually. this is more weird than you might think. Find your terminal and remove the var/cache/dev directory:

What the heck is this? Internally, Symfony caches things in this directory. And. you normally don’t need to think about this at all: Symfony is smart enough during development to automatically rebuild this cache whenever necessary. So. why am I manually clearing it? Well. because we copied my file. and because its «last modified» date is older than our original base.html.twig , Twig gets confused and thinks that the template was not updated. Seriously, this is not something to worry about in any other situation.

Referencing CSS Files

And when we refresh. there it is! Ok, it’s still pretty ugly. That’s because we’re missing some CSS files!

In the tutorial/ directory, I’ve also prepped some css/ , fonts/ and images/ . All of these files need to be accessed by the user’s browser, and that means they must live inside public/ . Open that directory and paste them there.

By the way, Symfony has an awesome tool called Webpack Encore that helps process, combine, minify and generally do amazing things with your CSS and JS files. We are going to talk about Webpack Encore. but in a different tutorial. For now, let’s get things setup with normal, static files.

The two CSS files we want to include are font-awesome.css and styles.css . And we don’t need to do anything complex or special! In base.html.twig , find the stylesheets block and add a link tag.

But wait, why exactly are we adding the link tag inside the stylesheets block? Is that important? Well, technically. it doesn’t matter: a link tag can live anywhere in head . But later, we might want to add additional CSS files on specific pages. By putting the link tags inside this block, we’ll have more flexibility to do that. Don’t worry: we’re going to see an example of this with a JavaScript file soon.

Читайте также:  Заполнить двумерный массив случайными числами python

So. what path should we use? Since public/ is the document root, it should just be /css/font-awesome.css :

Do the same thing for the other file: /css/styles.css :

It’s that simple! Refresh! Still not perfect, but much better!

The Not-So-Mystical asset Function

And now I’m going to slightly complicate things. Go back into PhpStorm’s Preferences, search for «Symfony» and find the «Symfony» plugin. Change the «web» directory to public — it was called web in Symfony 3.

This is not required, but it will give us more auto-completion when working with assets. Delete the «font-awesome» path, re-type it, and hit tab to auto-complete:

Woh! It wrapped the path in a Twig asset() function! Do the same thing below for styles.css :

Here’s the deal: whenever you link to a static asset — CSS, JS or images — you should wrap the path in this asset() function. But. it’s not really that important. In fact, right now, it doesn’t do anything: it will print the same path as before. But! In the future, the asset() function will give us more flexibility to version our assets or store them on a CDN.

In other words: don’t worry about it too much, but do remember to use it!

Installing the asset Component

Actually, the asset() function does do something immediately — it breaks our site! Refresh! Ah!

The asset() function comes from a part of Symfony that we don’t have installed yet. Fix that by running:

This installs the symfony/asset component. And as soon as Composer is done. we can refresh, and it works! To prove that the asset() function isn’t doing anything magic, you can look at the link tag in the HTML source: it’s the same boring /css/styles.css .

There is one other spot where we need to use asset() . In the layout, search for img . Ah, an img tag! Remove the src and re-type astronaut-profile :

Perfect! Refresh and enjoy our new avatar on the user menu. There’s a lot of hardcoded data, but we’ll make this dynamic over time.

Styling the Article Page

The layout is looking great! But the inside of the page. yea. that’s still pretty terrible. Back in the tutorial/ directory, there is also an article.html.twig file. Don’t copy this entire file — just copy its contents. Close it and open show.html.twig . Paste the new code at the top of the body block:

Check it out in your browser. Yep! It looks cool. but all of this info is hardcoded. I mean, that article name is just static text.

Let’s take the dynamic code that we have at the bottom and work it into the new HTML. For the title, use > :

Below, it prints the number of comments. Replace that with > :

Oh, and at the bottom, there is a comment box and one actual comment. Let’s find this and. add a loop! For comment in comments on top, and endfor at the bottom. For the actual comment, use > :

Читайте также:  Python text file example

Delete the old code from the bottom. oh, but don’t delete the endblock :

Let’s try it — refresh! It looks awesome! A bunch of things are still hardcoded, but this is much better.

It’s time to make our homepage less ugly and learn about the second job of routing: route generation for linking.

Leave a comment!

I came across your comment(s) as I was tearing my hair out over a similar issue. I ended up going through all my additional ini files (check phpinfo() for a list of yours), and removing the contents of each one (restart server between each edit) until finally it worked.

The cause of my issue was
«zlib.output_compression = On»

I commented this out for now.

Hi! I have a problem removing the cache. I insert the code rm -rf var/cache/dev/* in the console, but it responds rm is not a known command

ok, solved. I was in cmd for windows so I installed bash to run that command. I’m very very noob at this

But why are you trying to remove cache with rm -rf var/cache/dev/* ?

Where can i find the tutorial example files?

Do you mean the course code? If so, there is a «download» button at the top right corner of this page. Click it, and then select «Course Code», you will get a zip file with 2 folders, the start and finish directory.

in the video at 6:20 we have src when you added > to it it loads the image.
I dont understand it. What’s going on ?

In my own project in one of twig files i specified the path images/. /img.jpg» and it worked. I did the same in another twig file and it didn’t worked.
It worked with asset function though but i want to drop asset func since it’s no longer recommended.

Excellent question :). Let me clear this up a little bit:

1) First, the asset() function IS still recommended. In fact, i still use it in our Symfony 5 tutorial :). It’s just not as commonly-needed anymore, because if you use Webpack Encore, then you have a different function you can use for your CSS and JS. But even in that case, you should still use asset() to point to images.

2) So let’s talk about what the asset() function does. Basically. it does two things:

A) If you deploy to a CDN (where your assets are hosted on a different domain), you can add a little bit of configuration and all your assets paths will now point to that domain. If you need this functionality, it's great - and you'll be happy that you used `asset()` everywhere. B) It detects whether your site is deployed at the root of your domain - e.g. example.com - or a sub-directory - e.g. example.com/sf-app-here. If it is under a sub-directory, it will automatically prefix all your paths with the subdirectory. So, `asset('images/astronaut-profile.png')` will become `/sf-app-here/images/astronaut-profile.png`. 

At first look, it probably seems like neither of these are related to your situation. But actually, (B) IS doing something right now. Basically, in «normal» situation (where your site lives at the root of your domain like example.com or localhost:8000), the asset function does this:

Читайте также:  Html тег meta атрибуты

Yup. For 99% of the situations, the asset() function is a fancy way of adding a «/» at the beginning of the path :). And THAT is what makes the difference in your situation. Basically, if you put /images/astronaut-profile.png on both templates, it would work in both places (because this is basically equivalent to using the asset() function. But using relative paths — like ../images/img.jpg is never a good idea. Why? Imagine you have a path like that in your layout (so, it’s loaded on every page). Look at these examples:

  • When I go to example.com/login, my browser will look for example.com/images/img.jpg (because it will look at the URL, go up one directory thanks to the «../», then add /images/img.jpg)
  • When I go to example.com/article/some-article, my browser will look for example.com/article/images/img.pjg (because it will look at the full URL, go up one directory to /article, then add «images/img.jpg»).

That’s a super long way of saying that putting relative paths in your template is a bad idea — and it’s one of the things that asset() helps with :).

Let me know if that makes sense!

Источник

Структура HTML-документа для создания сайта (шаблон)

Структура HTML-документа определяет базовый «скелет» для будущего сайта, вариацию которого мы рассмотрим в данном материале. Код выполнен по стандарту HTML5 и кратко изложены основные тезисы элементов. Он подойдет как для начинающего верстальщика в целях разобраться, что собой представляет каркас страницы, так и профессионального вебмастера в качестве быстро используемого шаблона в своих работах.

Шаблон «скелета» HTML-страницы

Приведем исходный HTML-код с некоторыми дополнительными вставками для дальнейшей визуализации с помощью CSS и JS:

        

Оцените статью