Sinless section php. Including files in PHP using include and require

When creating sites on self-writing (without using frameworks, CMS, and other fashionable things that simplify the life of web developers), we are faced with the problem of making edits to the site when there are a lot of pages.

So that we do not have to change the same parts of the site in each of the page files, we can use convenient PHP instructions that allow us to include files with the necessary code in all pages with literally one line of code. Then, by changing the contents of the included file, we change the code on all pages of the site. Convenient, no matter how you look.

Now let's take a closer look at how to connect files:

Using include and require

You will not be able to find a fundamental difference between these two instructions with all your desire, but there are nuances:

If an error occurs during the execution of the require command, the parser will receive a fatal error response and the execution of the page code will stop, while include will only issue a warning and the file execution will continue (the file will simply not be connected).

Let's take a simple example for a better understanding of the topic.

We have our minisite in which the header and footer are the same on all pages, and the body of the document changes.

We create files header.php and footer.php in which we put the code that will be the same on all pages, and in the files index.php and newpage.php we will connect the static parts. As a result, we get:

Header.php content

< header> < nav> < a href= "newpage1.php" title= "menu item" >menu item < a href= "newpage2.php" title= "menu item" >menu item < a href= "newpage3.php" title= "menu item" >menu item

Footer.php content

< footer> < p>Made by us

Content of other pages of the site

Minisite

Lots of useful information

As a result of loading our page, we get the following picture:

As we can see, everything works great.

I would like to draw your attention to the fact that we ran the example on the local Denwer server, since PHP requires a server with its support for PHP to work. If you create a website in a simple folder on a PC, nothing will work.

In the above example, we used the require header and the footer include. What to use on your sites is up to you. As already mentioned, there is not much difference between them. Unless require is considered a somewhat stricter statement.

In fact, the line simply copies the entire contents of the file, the path to which we indicate, into the document in which it is located.

Using include _once and require _once

When working on the site, problems may arise due to the fact that the same piece of code is included in the same file repeatedly.

Suppose this happened due to the fact that several people worked on the site, and when the codes were merged, such an incident came out ...

Developers often use include_once and require_once statements to eliminate the possibility of such problems. The principle of operation for them is exactly the same as for include with require, but if the file in such an instruction has already been connected to ours, then the re-connection will not occur.

The disadvantages of this method include the fact that it is slower and more computationally intensive than its predecessors include with require, since it becomes necessary to remember all included files and compare them to avoid code duplication.

On a note

  • To make it easier to distinguish between the files of the site pages and the files of their fragments, which we include in them, the usually included files add an inc part in the name. Considering this approach in our example, we would get the header.inc.php file from the header.php file and so on. This approach can make it much easier to understand the structure of the site in the future.
  • The code from the file we are connecting inherits the scope of the line in which it is connected. Tobish just inside the page it will have a global scope, and inside the function it will have a local one.
  • We can use include with require wherever we want. Even inside scripts.
Document table of contents

1. config_load function

Syntax:
(config_load file = "filename")

This function is used to load variables from configuration files into a template. In addition to the name of the loaded file, this function can have several additional parameters. For example, the section parameter, which specifies the name of the section to load. More information on these and other parameters can be obtained from the Smarty documentation.

Example:
(config_load file = "task.conf")

2. Capture function

Syntax:

(capture name = "block_name"
assign = "variable_name") ...
(/ capture)

This function is designed to collect the output of the template into a variable instead of displaying it on the screen.

Anything between (capture name = "varname") and (/ capture) will be written to a variable named varname. The content captured in this way can be used in the template using the special variable $ smarty.capture.varname, where varname is the value passed to the name attribute of the capture function. If no variable name is specified, the name default will be used.

The second parameter assign specifies the name of the variable to which the captured output value will be assigned. This parameter, like name, is optional.

3. Section function

Syntax:

(section name = "section_name"
loop = "variable_for_out_number_iterations"
[, start = "start_position_index"]
[, step = "step"] [, max = "maximum_iterations"]
[, show = "show_or_section"]) ...
(/ section)

Section Section is a loop for traversing array elements. The required parameters are name, which is used to set the section name, and loop, which is a variable that determines the number of loop iterations.

As a rule, loop is an array variable, and the number of section iterations is equal to the number of elements of this array. To display a variable inside a loop, you need to indicate the section name in square brackets after the variable name.

(section name = art loop = $ title)

Title: ($ title)

(/ section)

Example 15.8. Loop to iterate over array elements

4. The foreach function

Syntax:

(foreach from = "array_name"
item = "current_item_name")
... (/ foreach)

In addition, you can use the additional attributes key - the name of the key for the current element of the array and name - the name of the loop, with which you can access its properties. The from and item attributes are required.

Foreach loops are an alternative to section loops. The foreach function works very much like the PHP foreach loop.
(foreach from = $ articles item = art)
Title: ($ art)

(/ foreach)

Example 15.9. Foreach loop

Foreach loops have their own properties. You can access them this way: ($ smarty.foreach.foreachname.varname), where foreachname is the name of the loop specified by its name parameter and varname is the name of the property.

5. Operator if, elseif, else

Syntax:

(if expression) action_block
(elseif expression1) action_block1
(else) action_block2
(/ if)

Operator action is almost the same as PHP operator if ... elseif ... else.

The following comparison operators can be used in expressions: eq, ne, neq, gt, lt, lte, le, gte, ge, is even, is odd, is not even, is not odd, not, mod, div by, even by, odd by, ==,! =,>,<, <=, >=. Each of them must be separated from the surrounding values ​​by spaces. You can use parentheses in expressions and call php functions.

(if $ name eq "Vasya")
Welcome, Vasya.
(elseif $ name eq "Petya")
Welcome, Petya.
(else)
Welcome. Who are you?
(/ if)

Example 15.10. If, elseif, else statements

(* this example will not work as there are no spaces around the comparison operators *)
(if $ name == "Vasya" || $ name == "Petya")
...
(/ if)
Example 15.11. Broken example

An article that explores the HTML section element from the sectioning category.

Purpose of the section element

The section element is used to create a section in a document that groups some subject content together. For each section in the document, its name (topic) should be indicated. This is usually done with headers (h1-h6 elements).

Section heading

Section content ...

Section elements are commonly used in the following situations:

  • to mark up sections within a section. For example, to mark up chapters in an article, tabs in a dialog box, sections in a dissertation, etc.
  • to group several sections into one thematic group. For example, to group the latest news on the site, comments on an article, etc.

Thus, the section element should only be used for some content if it has a heading and is part of something else.

Using the section element

For example, consider a snippet of page code that contains an article with comments. Each of the comments posted by the user on the page contains some complete content and therefore can be considered an article element. But, at the same time, all comments represent a certain thematic group, and therefore they can be placed in the section element, i.e. this element will group all these comments on the page together.

Article title

Comments (1)

Comment header

Comment text ...

Comment header

Comment text ...

Article Title Comments Comment Title Comment Title

For example, consider using section elements to create sections within an article element:

Book title

First chapter

Chapter two

Chapter Three

Appendix A

Appendix B

The above example will have the following outline:

Book Title Chapter One Chapter Two Chapter Three Appendix A Appendix B

Limitations when using the section element

The section element in HTML 5 is not a generic element for grouping content, i.e. it should not be used to wrap any content you like. Its main purpose is to add semantics to the document and create its outline.

When an author needs to group content just to style or manipulate it in JavaScript, the best place is for them to use the div element. The div element, unlike the section element, does not add semantics to the document and does not participate in creating its outline (outline).

Difference between section and article elements

The section and article elements, while at first glance seem very similar, have different semantic meanings. The article element is intended to group content that is complete, self-contained, and can be viewed separately from the rest of the page content. And the section element carries a different semantic meaning, it is intended to group content that is an integral part of something else.

But how can an author know what some content on a page is? Let's look at this with an example of a snippet of an article. A snippet is part of an article, and therefore a section element must be used to group its content. But the same fragment, already left as a commentary, will represent something whole, complete. Therefore, in this context, the article element can be used to group it. But, of course, one can reason, and vice versa. Therefore, which element to use to group content is in most cases dependent on your subjective opinion as an author. But the most important thing in this approach is to maintain the chosen position. Therefore, the more consistent the author is in creating the structure, the more sense he can put into it.

). Each tag (section) must have a pair (/ section)... The required parameters are name and loop... The name of the loop (section) can be any name consisting of letters, numbers and underscores. Cycles (section) can be nested and nested names (section) must be unique among themselves. Variable loop(usually an array of values) determines the number of loop iterations. When printing variables inside a section, the section name must be indicated next to the variable name inside square brackets. (sectionelse) is executed if the parameter loop contains no values.

Attribute name Type of Mandatory Default Description
name string Yes n / a Section name
loop mixed Yes n / a A value that determines the number of loop iterations.
start integer No 0 The index of the position at which the loop will start. If the value is negative, then the starting position is calculated from the end of the array. For example, if there are 7 elements in a loop variable and the start attribute value is -2, then the start index will be 5. Invalid values ​​(values ​​outside the array) are automatically truncated to the nearest valid value.
step integer No 1 The stride value that is used to traverse the array. For example, step = 2 indicates a traversal of the array by elements 0,2,4 ... If the step is negative, then the array will be traversed in the opposite direction.
max integer No 1 The maximum number of loop iterations.
show boolean No true Indicates whether to show this section or not

Note

Starting with Smarty 1.5.0, the syntax of session property variables has been changed from (% sectionname.varname%) to ($ smarty.section.sectionname.varname). The old syntax is still supported, but you will only see examples of the new syntax.

index is used to display the current index of the array, starting at zero (or at the start attribute, if specified) and increasing by one (or by the value of the step attribute, if specified).

Technical Note

If the step and start attributes are not specified, then index is the same as the iteration section attribute, except that it starts at 0 instead of 1.

iteration is used to display the current iteration number of the loop.

Note

This value is independent of the start, step, and max properties, unlike the index property. Also, iterations start at one, rather than at zero like indices. rownum is a synonym for the iteration property, they work the same way.

Example 7.38. property (section) iteration

assign ("custid", $ id); ?> (section name = cu loop = $ custid start = 5 step = 2) iteration = ($ smarty.section.cu.iteration) index = ($ smarty.section.cu.index) id = ($ custid)
(/ section)

The result of this example:

Iteration = 1 index = 5 id = 3005
iteration = 2 index = 7 id = 3007
iteration = 3 index = 9 id = 3009
iteration = 4 index = 11 id = 3011
iteration = 5 index = 13 id = 3013
iteration = 6 index = 15 id = 3015

This example uses the iteration property to output the table title every five lines (uses (if) with the mod operator).

(section name = co loop = $ contacts) (if $ smarty.section.co.iteration% 5 == 1) (/ if) (/ section)
Name>HomeCellEmail
view ($ contacts.name) ($ contacts.home) ($ contacts.cell) ($ contacts.email)