Juicebox error config file not found

Juicebox Error: Config file not found. [SOLVED] (Page 1) — Juicebox-Lite Support — Juicebox Support Forum — Get support on using Juicebox

Pages 1

You must login or register to post a reply

1 2016-09-17 01:38:16 (edited by Scott 2016-09-17 03:05:28)

  • Scott
  • Member
  • Offline
  • Registered: 2016-09-13
  • Posts: 6

Topic: Juicebox Error: Config file not found. [SOLVED]

I’m trying to learn Juicebox-Lite prior to purchasing the Pro version and then getting Showkase
If someone could help me with my below problem, it will be greatly appreciated.
The gallery previews as I would like it when I view it locally after the publish/save step
I have placed the Juicebox folder in the public_html folder on my website and uploaded w/Filezilla
to the sam folder
The code I embedded:

<!—START JUICEBOX EMBED—>
<script src=»/Juicebox/jbcore/juicebox.js»></script>
<script>
new juicebox({
containerId : «juicebox-container»,
galleryWidth: «100%»,
galleryHeight: «100%»,
backgroundColor: «#222222»
});
</script>
<div id=»juicebox-container»></div>
<!—END JUICEBOX EMBED—>

The page:
http://bakerracingpix.com/2016-clay-school.html

Thank you in advance for any and all help

2 Reply by Steven @ Juicebox 2016-09-17 09:10:18

  • Steven @ Juicebox
  • Juicebox Support Team
  • Offline
  • Registered: 2012-04-24
  • Posts: 5,804

Re: Juicebox Error: Config file not found. [SOLVED]

By default (using the regular embedding code), Juicebox will look for a file named ‘config.xml’ in the same directory as the page containing the gallery’s embedding code. (Your gallery structure does not have a ‘config.xml’ file in this location.)

If you move or rename this file, then you can point towards it using a configUrl option in your embedding code.
When using a configUrl, all paths in the ‘config.xml’ file will still be relative to the embedding code page.

As you have uploaded an entire Juicebox gallery (your ‘Juicebox’ folder) to your web server, you can point towards this folder using a baseUrl option. Please see here for details.
When using a baseUrl, all paths in the ‘config.xml’ file will be relative to the baseUrl so there is no need to make any modifications to any gallery files.

Just change your gallery’s embedding code to the following (add the baseUrl entry pointing towards the gallery folder) and all should be well.

<!--START JUICEBOX EMBED-->
<script src="/Juicebox/jbcore/juicebox.js"></script>
<script>
    new juicebox({
        baseUrl: "/Juicebox/",
        containerId: "juicebox-container",
        galleryWidth: "100%",
        galleryHeight: "100%",
        backgroundColor: "#222222"
    });
</script>
<div id="juicebox-container"></div>
<!--END JUICEBOX EMBED-->

Short descriptions of configUrl and baseUrl can be found in the Embed Options section of the Config Options page.

3 Reply by Scott 2016-09-18 02:24:16

  • Scott
  • Member
  • Offline
  • Registered: 2016-09-13
  • Posts: 6

Re: Juicebox Error: Config file not found. [SOLVED]

Steven:
THANK YOU!!!
Now I’ll play with this and then go the Pro edition and life will be good.

4 Reply by Steven @ Juicebox 2016-09-18 10:15:58

  • Steven @ Juicebox
  • Juicebox Support Team
  • Offline
  • Registered: 2012-04-24
  • Posts: 5,804

Re: Juicebox Error: Config file not found. [SOLVED]

You’re welcome!
I’m glad you’ve got it working.
Thank you for letting me know.

5 Reply by Scott 2016-09-20 02:14:10 (edited by Scott 2016-09-20 02:54:28)

  • Scott
  • Member
  • Offline
  • Registered: 2016-09-13
  • Posts: 6

Re: Juicebox Error: Config file not found. [SOLVED]

Now that I think I figured out how to do one page, I’m asking for opinions on the best way for me to proceed.
My site is pages of events and I’m wondering what the best way is to save the images, etc.
I renamed the first file I did («Juicebox») to «Clay_School» where all the pertinent files, including images are saved (see below)
By doing this, I know that all the Clay School images are in one place. (I’m not sure I really need to do this)
Should I use this method for all the different pages or is there a more efficient (easier) way to do it?

<!—START JUICEBOX EMBED—>
<script src=»/Clay_School/jbcore/juicebox.js»></script>
<script>
new juicebox({
baseUrl: «/Clay_School/»,
containerId: «juicebox-container»,
galleryWidth: «100%»,
galleryHeight: «100%»,
backgroundColor: «rgba(0,0,0,1)»
});
</script>
<div id=»juicebox-container»></div>
<!—END JUICEBOX EMBED—>

Here is the page:
http://www.bakerracingpix.com/2016-clay-school.html

Thanks in advance for any and all replies!

6 Reply by Steven @ Juicebox 2016-09-20 11:09:46

  • Steven @ Juicebox
  • Juicebox Support Team
  • Offline
  • Registered: 2012-04-24
  • Posts: 5,804

Re: Juicebox Error: Config file not found. [SOLVED]

Should I use this method for all the different pages or is there a more efficient (easier) way to do it?

I guess it’s a personal thing (organizing files on a web server) and there are certainly a number of different ways you could arrange things with the availability of the configUrl and baseUrl configuration options and the possibility of storing all your images in a single folder.

However, here’s what I’d do.
I’d keep each gallery in a separate folder and embed the galleries using the baseUrl method (as you currently do for your ‘Clay_School’ gallery).
I find that this helps to keep things organized. You know exactly where all the files for each gallery are. There is no need to search through a single folder of images wondering which images are for which gallery.
Also, if you ever need to edit or update the gallery in the future, all you need to do is swap out the gallery folders (new for old).

I’d also have all galleries share a single instance of the ‘jbcore’ folder. Please see the Using an External jbcore Folder for details.
Basically, you’d just upload a single ‘jbcore’ folder for all your galleries to share.
For each gallery, you’d just point towards the shared ‘jbcore’ folder.
This has the advantage of being able to upgrade all the galleries on your web site at once (for example when a new version of Juicebox is released) by replacing just a single ‘jbcore’ folder on your server.
This means that the ‘jbcore’ folders in all your gallery folders are redundant. You can leave them in place if you want (they’ll do no harm other than take up a bit of space) or delete them.

I hope this helps.

7 Reply by Scott 2016-09-21 00:08:10 (edited by Scott 2016-09-21 00:08:26)

  • Scott
  • Member
  • Offline
  • Registered: 2016-09-13
  • Posts: 6

Re: Juicebox Error: Config file not found. [SOLVED]

I guess it’s a personal thing (organizing files on a web server) and there are certainly a number of different ways you could arrange things with the availability of the configUrl and baseUrl configuration options and the possibility of storing all your images in a single folder.

Your suggestion is right in line with what I was thinking and planning on using. It keeps everything well organized and easy to change/update.

Thank you for the timely responses with the answers & suggestions to my questions. Just one of the reasons I will be going to Juicebox Pro along with Showkase on Friday.

8 Reply by Steven @ Juicebox 2016-09-21 09:47:52

  • Steven @ Juicebox
  • Juicebox Support Team
  • Offline
  • Registered: 2012-04-24
  • Posts: 5,804

Re: Juicebox Error: Config file not found. [SOLVED]

You’re welcome!

If you use Showkase for your website and Juicebox galleries, then there will be no need to worry about any embedding code or file structure. Showkase will handle it all for you.

Don’t forget that Showkase can be purchased as Showkase-Standard (which comes with Juicebox-Lite and SimpleViewer-Standard, the free versions) or Showkase-Pro (which comes with Juicebox-Pro and SimpleViewer-Pro). The only difference between Showkase-Standard and Showkase-Pro is the bundled viewers.

If you do purchase Showkase, be sure to check out the Getting Started guide here.

Pages 1

You must login or register to post a reply

I have installed the module as well as jbcore at /libraries/juicebox and can confirm that the library is properly installed. I created a view with a multi-value image field formatted as a Juicebox Gallery. I have set options at /admin/config/media/juicebox. I have set options on my field as well. Nevertheless, I am getting a «Juicebox Error: Config file not found.» message.

Comments

  • Log in or register to post comments

jhmnieuwenhuis’s picture

I do not now why, but after uninstall and reinstall of this module, the error dissapeared.

Regards,

Hans

  • Log in or register to post comments

rjacobs’s picture

Category: Bug report » Support request
Status: Active » Postponed (maintainer needs more info)
  • Log in or register to post comments

jhmnieuwenhuis’s picture

  • Log in or register to post comments

smustgrave’s picture

I ran into this issue recently. When using the Juicebox module 8.x-2.x-dev and Libraries API 8.x-3.0-alpha1 the juicebox file is never found. But using Juicebox 8.x-2.0-beta3 seemed to work for now.

  • Log in or register to post comments

bdawg8569’s picture

I know this is a pretty old thread, but i’m getting this upon updating to Juicebox 3 (tried dev and 3.0-alpha2. Anyone else having this issue? The status report shows that i’m using Lite 1.5.1 and that it can find it. But when I hit a view page using the plugin, I get the config file not found problem, and i’m not sure how to go about it. I tried to uninstall and reinstall, and no luck.

  • Log in or register to post comments

fkelly12054@gmail.com’s picture

But when I hit a view page using the plugin, I get the config file not found problem

The rest of the posts in this thread are really outdated. Can you provide some more info. on what’s happening. I’d prefer to look in the alpha2 code (though I believe it is almost identical to the dev code). First where did you put the js library? Sites/all/libraries or the /libraries folder at the root of your site? You have the juicebox.js file there? Which «status report» are you referring to?

When you say you hit the view page «using the plugin» what exact steps are you using? How is your gallery set up? Do you have an xml file and an images and thumbnails directory out in sites/files. Were these created with Juicebox builder on a PC? Or how else are you creating the gallery?

The version on this issue is set to 8.x-2.0-beta. Only the alpha version and the latest dev version support library discovery within Juicebox itself. The rest rely on a separate libraries module. Anything older will not work in Drupal 9.

At any rate, if you can provide reproducible steps I will look into it.

  • Log in or register to post comments

fkelly12054@gmail.com’s picture

Version: 8.x-2.0-beta2 » 8.x-3.0-alpha2
Status: Postponed (maintainer needs more info) » Needs work

Changing status and Version.

  • Log in or register to post comments

bdawg8569’s picture

Hey fkelly,
Thanks for the reply. Since this was an upgrade to D9, my D8 site already had the JS library in the sites/all/libraries/juicebox/juicebox.js and the status report page (admin/reports/status) shows that there are no problems with the library. It says «JUICEBOX JAVASCRIPT LIBRARY — Lite 1.5.1».

The page where i’m using juicebox and getting the problem is on a page built with a Drupal view. The view is simply pulling media entities of type «Image» and displaying them with the Juicebox Gallery format.

You can see the page at https://clft.org/visual-tour if you like. This is the D8 site that is still running Juicebox 8.x-2.0-beta4.

Thanks for your help, let me know if I can provide any other information.

  • Log in or register to post comments

fkelly12054@gmail.com’s picture

Thanks. Your Drupal 8 site looks good by the way.

Just to be sure: your Drupal 8 site with beta4 of Juicebox still works? But when you try a Drupal 9 site with the alpha2 release the same view no longer works?

I will try to simulate that. We did a little work testing views a year ago during the transition to the alpha2 release to support Drupal 9. But I can’t say we were able to test it comprehensively especially with the «newer» media entities. The whole area of Juicebox code relating to views is a bit obscure to me. Juicebox has to «know» which images are being processed by the views module but views keeps some of the info private. There are comments in the code relating to the limitations of this «situation» that I may need to explore further. But first I’ll try to replicate the situation.

Privately I’ve been working back through the alpha2 code eliminating some remaining issues with meeting Drupal coding Standards (PHPCS) and trying to resolve issues with broken functional tests that we need to resolve before moving to a beta or stable release for Drupal 9. The views issues will be added to that.

  • Log in or register to post comments

bdawg8569’s picture

That is correct, the Drupal 8 site still works just fine. In fact, i’m still on drupal 8 now even, but upgraded juicebox in preparation for the move to D9.

Ironically, i just removed some stuff from the view, and then saved it again, and it’s now working. I am pretty sure i rebuilt this entire view last week after removing it. I don’t know what is different, but it is working right now on juicebox 3.

I am going to move these changes up to the development server and see if its ok on there as well. Thanks for your help. I will post again if it goes wonky on me.

  • Log in or register to post comments

fkelly12054@gmail.com’s picture

«but it is working right now on juicebox 3»

Good to know that. Let us know how your testing goes. Since I posted earlier I’ve been vaguely recalling our experiments and tests from December 2020. I had created a content type named «Quick Juicebox». I had an image field and could add multiple instances of it. I just recreated another copy (instance) of that content type. Added two images to it. In the view set up I made the Formatter drop down box pick Juicebox Gallery as the format. The other options were:

Main Image Style
JUICEBOX Pro Multi-size
The style formatter for the main image.

Thumbnail Style
Gallery Thumbnail
The style formatter for the thumbnail.

Caption Source
Img — Alt text
The image value that should be used for the caption.

Title Source
File Filename
The image value that should be used for the title.
(where the italicized values are the ones I filled in)

Saving the view allowed me to view the quick juicebox content type with results similar to what was on your web page. If I recall correctly the key was making the Format field be «Juicebox Gallery». I’m pretty sure you could create multiple content items of type «quick juicebox» (or whatever you call it) and put in a field to use for selecting on in the view.

  • Log in or register to post comments

bdawg8569’s picture

I completed the upgrade to 9 and its all working. I don’t know what the hiccup was that i had for a bit, but its not doing it any longer. Thanks so much for all your help!

  • Log in or register to post comments

fkelly12054@gmail.com’s picture

Status: Needs work » Closed (cannot reproduce)

Thanks for reporting back to us. I will close this. I am still suspicious that there may be some lurking deficiencies in the way Juicebox works with views but we can iron that out as we move towards a stable D9 release.

Closing this issue as «fixed» for now.

  • Log in or register to post comments

На чтение 4 мин. Просмотров 16 Опубликовано 15.12.2019

Getting error «Config.h file not found, lexical or preprocessor error.»

I am running app in the device from the xcode project.

I have google and found many solutions but haven’t worked, I tried this

And when I try to run in the iOS simulator getting this error

Tried to follow the above url but didn’t work.

Please let me know how to solve the issue. Thanks

Содержание

  1. Brought to you by: amecky, terrydye
  2. Group
  3. Searches
  4. #29 config file not found
  5. Discussion
  6. Comments
  7. Comment #1
  8. Comment #2
  9. Comment #3
  10. Comment #4
  11. Comment #5
  12. Comment #6
  13. Comment #7
  14. Comment #8

Brought to you by: amecky, terrydye

  • Create Ticket
  • View Stats

Group

Searches

#29 config file not found

Hallo,
my config file is not found,

I get the error:

java.io.FileNotFoundException:
C:ProgrammeTomcat%205.0webappspaneltoolWEB-INFclassesconfig.xml
(Das System kann den angegebenen Pfad nicht finden)

It seems the problem is the space between Tomcat and
5.0 in my tomcat installation folder!

I use Windows XP, and jdk 1.5.

Discussion

Logged In: YES
user_ >

A little more information about the problem would be quite
helpful.

— where is the config.xml file? is the path above correct?
is the path something you set, or something that jConfig
discovered?
— how are using jConfig in your code?

// und hast Du vielleicht andere Ideen, wie wir dir
vielleicht helfen könnten?

Logged In: YES
user_ >

No response to question. This issue will be closed.

Getting the following error on node view:

Juicebox Error: Config XML file not found.

Used Chrome console and was able to see that the XML was being returned — however, with an empty first line:

I replaced the domain with «x» since it’s internal for testing. Do you think that maybe the issue? If so, any suggestions on what could be causing this?

Thanks in advance!

Issue summary: View changes
  • Log in or register to post comments

Issue summary: View changes
  • Log in or register to post comments

This is resolved. After spending little over an hour — (ugh) — it ended up being in our settings.php which we had error_reporting code at the top with a closed ?> and a blank line after it

  • Log in or register to post comments

Assigned: Unassigned » pdesai
Status: Active » Fixed
  • Log in or register to post comments

Assigned: pdesai » Unassigned
Category: Bug report » Support request

Yeah, if anything is printed to the screen before the normal page headers, such as whitespace, this can cause problems. It often goes undetected until something using XML is involved (such as this module), as the XML parsers in most browsers will not gracefully ignore that whitespace. This comes up form time-to-time and unfortunately there is not much that can be done to avoid or detect it (that I know of). More info here: https://drupal.org/comment/7977753#comment-7977753

  • Log in or register to post comments
Status: Fixed » Closed (fixed)

Automatically closed — issue fixed for 2 weeks with no activity.

  • Log in or register to post comments

Status: Closed (fixed) » Active

I am sorry to open this issue again but I am a little confused. I have juicebox working just fine when using the formatter in the content type full display but if I use it in a views attachment as a formatter on an image field I get Juicebox Error: Config XML file not found.
If this is a white space problem why is it only affecting the views field formatter and not the content type full display field formatter?

  • Log in or register to post comments

@Road Kill, if you are seeing inconsistent errors such that the field formatter behaves differently than the views plugin then it’s most likely that something else is going on. Though the whitespace issue is a common explanation for the «Config XML not found» error, it’s certainly not the only one. If the problem persists I suggest opening-up a separate issue thread and try to post as many details as you can about your case there. One of the best things that you can do as part of that will be to share a link to a public page that demonstrates the problem (if possible).

Создать несложный сайт с динамическим выводом контента можно без особых усилий всего за пару дней, обладая знанием языка SSI. Этот язык прост в освоении, поскольку имеет простой синтаксис и небольшое количество команд.

Галерея скриншотов

Язык SSIТот, кто знает HTML и CSS, может сверстать веб-страничку любой сложности. Если у Вас простой сайт-визитка, то, в принципе, большего Вам и не надо, – главное, чтобы было красиво :).

Но, если планируется, что сайт будет иметь не один десяток страниц, то тут уже перед нами встает проблема: как уследить за тем, чтобы код на всех страничках был одинаковым, а, главное, что будет, если в один прекрасный момент придется менять какие-то нюансы нашего кода?

Согласитесь, ручная обработка пары десятков страниц, для изменения, например, содержимого секции <HEAD>, занятие не из самых приятных… Конечно, Вы можете воспользоваться мощными утилитами для пакетной замены текста, но проще было бы использовать возможности разнообразных серверных языков программирования.

Самым популярным на сегодняшний день является язык PHP. Это практически полноценный язык программирования, который предоставляет богатые функциональные возможности, но у него есть один недостаток – страницы на PHP грузятся почти вдвое дольше, чем на простом HTML.

Если планируется создать сложный Интернет-портал, то без PHP, увы, не обойтись, но для реализации несложных сайтов с динамическим выводом контента некоторые разработчики предпочитают другой язык – SSI.

Расшифровывается название, как Server Side Includes, что на русский можно перевести, как «включения на стороне сервера». Этот язык отличается своей относительной простотой в освоении, а также скоростью обработки. Страницы на SSI собираются примерно на 25–50% быстрее, чем на PHP!

В некоторых случаях они почти не проигрывают по скорости обычному HTML-коду. Но, в то же время, SSI позволяет свести к минимуму дублирование различных фрагментов кода, таких как блоки навигации, шапка и подвал сайта.

По сути, создавая новые странички с контентом на SSI, мы будем записывать в них только нужные значимые данные, например, статьи или обзоры, а остальные фрагменты странички при помощи специальных команд будут сами подгружаться, автоматически формируя привычный нам вид HTML-кода.

Подготовка к созданию сайта на SSI

Итак, мы решились :)… Сейчас мы с Вами в качестве примера создадим небольшой сайт про то, как создавать сайты на SSI ;) Контент для быстроты работы будет позаимствован из всезнающей Википедии, а сам сайт будет создан на чистом HTML и CSS, с использованием мощностей их последней версии (HTML5 и CSS3, соответственно).

Для работы нам потребуется небольшой набор программ:

  • локальный веб-сервер (я использую Денвер) для реализации SSI;
  • текстовый редактор (я использовал AkelPad, но Вы можете выбрать для себя любой другой);
  • веб-браузер для просмотра результатов нашей работы (я верстал сайт под Google Chrome, поэтому рекомендую использовать подобные ему веб-обозреватели для корректного отображения кода упомянутого в данной статье).

Если Вы разбираетесь в HTML, то Вам проще всего будет сразу сверстать главную страничку будущего сайта, чтобы было, откуда брать фрагменты кода (хотя, в будущем Вы сможете обходиться и без этого, напрямую верстая сразу в SSI). Мой пример странички в HTML выглядит примерно так:

HTML-макет странички сайта

Для простоты воспроизведения Вами данного урока в оформлении я не использовал никаких картинок, – только чистый код, который мы разместили в двух файлах: index.html и style.css (находятся в архиве в папке «Простой HTML»). В браузере жмем CTRL+U и смотрим исходник странички:

HTML-код макета странички сайта

Как видим, особых сложностей и изысков в верстке нет. Практически все элементы, исключая только логотип, идут друг за другом по вертикали, что исключает лишние заморочки с позиционированием, а все оформление вынесено в отдельный файл стилей.

Подключение блоков кода посредством SSI

Теперь, внимательно посмотрим на вышеприведенный код и прикинем, какие элементы будут у нас повторяться на всех страницах нашего сайта. По сути, на всех страничках меняется только содержимое тега <article>, все остальное можно вынести и подключать динамически. Для этого в SSI существует простая команда (кстати, аналогичная PHP) – «include»:

<!—#include virtual=»имя_страницы.shtml»—>

На примере данной функции рассмотрим синтаксис SSI. Он, в принципе прост: для предотвращения вывода браузером SSI-включений они экранируются обычными HTML-комментариями, а внутри еще и дополнительным символом «#». Затем идет непосредственно команда и ее атрибуты (почти так же, как в обычных HTML-тегах).

Что касается именно команды «include», то она может иметь один из двух атрибутов: «virtual» и «file». Оба они служат для указания ссылки на нужный документ, текст которого должен быть вставлен, но «file» может содержать только относительный путь, поэтому использование «virtual», как более функционального атрибута, будет предпочтительнее.

Попробуем применить на практике, только что полученные данные. Для этого установим веб-сервер (если Вы его еще не устанавливали) и создадим в папке «home» новую папку с названием нашего сайта (у меня это – ssi.site). В папке сайта создадим еще одну директорию с именем «www» (прочитать подробнее о работе с Денвером можно здесь). В нее мы и будем складывать файлы нашего сайта.

Кстати о файлах… Для работы SSI требуется чтобы они имели расширения .shtml, .shtm или .stm.

Весь код созданной нами странички можно рассовать по трем файлам:

  1. В «header.shtml» разместится код шапки и навигации;
  2. В «general.shtml» будет находиться текст статьи (этот файл мы потом упраздним);
  3. В «footer.shtml» поместим подвал сайта.

Теперь для того чтобы собрать все это в единое целое нам будет достаточно создать четвертый файл index.shtml, который будет отвечать за отрисовку главной страницы сайта, со следующим содержимым:

<!—#include virtual=»header.shtml»—>
<!—#include virtual=»general.shtml»—>
<!—#include virtual=»footer.shtml»—>

Таким образом, мы получим следующую структуру документов:

Структура кода главной страницы SSI-сайта

Как видим, SSI посредством всего трех строчек кода позволяет собрать полноценную веб-страницу из заранее подготовленных фрагментов.

Однако, дабы не плодить лишних сущностей, мы можем еще немного оптимизировать код файла «index.shtml», вставив вместо второй директивы содержимое файла general.shtml.

Таким образом, у нас останется всего два файла («хэдэр» и «футер»), которые можно подключать куда угодно, а текст статьи будет помещен непосредственно в вызываемом документе! То есть, окончательный код всех значимых страничек на нашем сайте будет иметь следующий вид:

<!—#include virtual=»header.shtml»—>
<article>Здесь текст статьи…</article>
<!—#include virtual=»footer.shtml»—>

Что мы выигрываем от этого? А то, что в случае добавления новых пунктов меню или изменений в заголовках/подвалах нам будет достаточно nпоправить всего два файла и их содержимое автоматом будет изменено на всех страницах!

Работа с переменными в SSI

Вставлять готовые блоки кода – это прекрасно, но иногда требуется, чтобы некоторые из них изменялись в зависимости от того, на какой странице находится посетитель нашего сайта. В SSI, как и в других языках программирования, это решается при помощи переменных.

Переменная – это заданное пользователем выражение, значение которого может изменяться в зависимости от конкретных условий. Предлагаю Вам рассмотреть принцип создания и использования переменных в SSI на примере реализации тега <title>, который отвечает за заголовок страницы.

Тег этот используется для каждой страницы в блоке <HEAD>, а его, как мы помним, мы вынесли в файл «header.shtml». Сейчас там задан фиксированный заголовок для главной страницы, и он выводится неизменным везде.

Попробуем исправить положение… Как Вы, наверное, догадались содержимое тега <title> нужно заменить переменной. Сделать это очень просто, достаточно вписать в него такие строки:

<title><!—#echo encoding=»none» var=»title»—></title>

Синтаксис выражения нам уже знаком, но команды – новые. Здесь основная команда – echo. Она, как и в PHP, служит для вывода любых переменных. Далее мы видим два атрибута. Атрибут «var» нужен для указания имени переменной, которую мы вызываем, и является обязательным.

Атрибут «encoding» – необязательный, но приносит неоценимую помощь тем, кто использует кодировку, отличную от WIN-2151.

По умолчанию, сервер преобразовывает все переменные в вышеуказанную кодировку и на выходе мы получаем английский текст (если он был, то он обычно не меняется) с кракозябрами вместо русских слов :(. Дабы этого не произошло, используем «encoding» со значением «none», тем самым отключая все преобразования!

Однако вызвать, то мы переменную вызвали, но ее пока не существует… Ее нужно еще и объявить. Для этого в самое начало каждой странички с уникальной статьей вставим строку примерно следующего содержания:

<!—#set var=»title» value=»SSI-сайт | Главная»—>

Здесь мы видим новую команду – «set». В SSI она служит для объявления пользовательских переменных. Она имеет два обязательных атрибута: уже знакомый нам «var» для указания имени переменной и «value».

Последний нужен для указания значения, которое будет присвоено объявленной переменной при ее вызове с текущей странички. Аналогичные строки вставляем во все значимые странички и в итоге получаем уникальные заголовки для каждой из них:

Динамический вывод заголовка странички сайта

Пример реализации динамического навигационного меню на SSI

В данном разделе мы кое-что узнаем о встроенных переменных SSI и условиях, а также рассмотрим пример создания при помощи этих новых знаний навигационного меню, которое будет изменять стиль кнопки при заходе на одноименную страничку.

Встроенных переменных или, как их еще называют, переменных окружения в SSI не очень много, но для реализации несложных задач – достаточно. Они позволяют работать с адресной строкой, куками, IP-адресами, временем и некоторыми заголовками.

Получить список всех встроенных переменных Вы можете, воспользовавшись командой printenv (то есть, <!—#printenv—>).

В нашем же случае нам нужна переменная «DOCUMENT_URI», которая отвечает за адрес запрошенной страницы. Для реализации изменений в меню навигации нам нужно придумать алгоритм. Алгоритмов может быть несколько, поэтому программирование – это своего рода искусство :). Я предлагаю следующий алгоритм:

Если мы находимся на определенной странице, то кнопка со ссылкой на эту страницу меняется на обычный блок, оформленный нужным нам образом, иначе кнопка остается со ссылкой, не изменяясь.

На языке SSI это можно выразить следующим условием:

<!—#if expr=»$DOCUMENT_URI=/index.shtml/» —>
<span class=»activ»>&nbsp;Главная&nbsp;</span>
<!—#else —>
<a class=»inactiv»
href=»index.shtml»>&nbsp;Главная&nbsp;</a>
<!—#endif —>

Как видим, здесь мы прописали условие для главной страницы сайта. Синтаксис остается все тот же, но появляются новые команды:

  • if – условный оператор, заменяющий слово «если»;
  • expr – атрибут, при помощи которого можно задать выражение, для которого создается условие;
  • else – условный оператор, который на «человеческий» язык можно перевести, как «во всех остальных случаях». Он позволяет задать действие, которое будет исполняться тогда, когда условия не соответствуют параметрам, заданным в «if» (не путать с оператором «elif», который позволяет задать дополнительное условие);
  • endif – обязательный оператор, который закрывает условие.

Обратите внимание, что в атрибуте «expr» переменные обязательно предваряются знаком доллара («$»), как в PHP.

Итак, при помощи вышеописанной конструкции мы задали условие, при котором изменяется не только стилевой класс, но и вообще тип элемента, точнее в зависимости от ситуации выводится один из двух элементов: либо ссылка, либо обычный текстовый блок.

Нам остается прописать такие же условия для каждой кнопки меню (оно у нас находится в блоке <nav>…</nav> в файле header.shtml), и мы получим динамическую навигацию на всем сайте:

SSI-меню сайта

Манипуляции со временем в SSI

Что удобно делать в SSI, так это производить разнообразные манипуляции со временем. Примерами таких действий могут быть:

  1. Вывод текущей даты и времени Вашего часового пояса в заданном формате.
  2. Вывод времени по Гринвичу.
  3. Вывод даты последней модификации документа.

Для вывода те кущей даты и времени нам достаточно воспользоваться встроенной переменной «DATE_LOCAL»:

<!—#echo var=»DATE_LOCAL»—>

Вывод будет осуществлен в формате: день (по английски), число-сокращенное название месяца-год часы:минуты:секунды часовой пояс. Однако этот формат легко настроить под свои нужды, используя команду «config» с атрибутом «timefmt».

Например, если нам нужно вывести время и дату в стандартизированном международном представлении, то команда будет иметь следующий вид:

<!—#config timefmt=»%Y-%m-%d, %H:%M:%S» —>

Результат будет примерно таким: 2013-08-01, 10:56:22. Как нетрудно догадаться, большие и маленькие буквы после значка «%» отвечают за вывод той или иной части даты, и, по сути, являются сокращением от английских названий этих частей.

Соответственно, большие буквы обозначают полный формат (например, для года %Y (сокр. от «year») это будет – 2013), а маленькие – сокращенный (%y выведет только число «13»).

Фрагменты можно разделять любыми знаками и символами, что делает настройку вывода даты максимально гибкой. Если Вы хотите больше узнать о возможностях настройки формата вывода даты, советую Вам почитать статью на Citforum.ru.

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

<!—#flastmod virtual=»index.shtml»—>

Если Вы внимательно читали статью, то помните, что атрибут «virtual» указывает путь к файлу, который требует определенной обработки. Здесь мы используем его для тех же целей – указания адреса файла, дату последней модификации которого мы хотим вывести.

Причем, атрибут «virtual» может содержать не только реальные адреса, но и переменные. Это дает нам возможность, например, динамически выводить дату последнего изменения страниц при помощи такого кода:

<!—#flastmod virtual=»$DOCUMENT_URI»—>

Применив эти знания на практике, мы можем, например, снабдить подвал нашего сайта (файл footer.shtml) полезной информацией:

Вывод времени в SSI

Немного поработав с форматированием текста, мы можем получить примерно такой итоговый вариант:

Окончатльный вид сайта

Достоинства и недостатки технологии SSI

Плюсы языка SSIПлюсы:

  • простота освоения;
  • небольшая нагрузка на сервер;
  • удобно реализовываются некоторые функции;
  • поддержка условий;
  • поддержка переменных (в том числе и переменных окружения).

Минусы языка SSIМинусы:

  • нет поддержки циклов;
  • нет возможности работы с файлами;
  • необходимость использования специфического расширения файлов.

Выводы

В свое время SSI был прорывом, но сейчас его почти вытеснил PHP. Однако, несмотря на это, некоторые сайты до сих пор используют данный язык, например, в связке с CGI-скриптами.

Да, SSI – несколько примитивен, но за счет своей примитивности он выигрывает в плане производительности и меньшей нагрузки на сервер, что порой бывает критично. Поэтому, если Ваш будущий сайт не нуждается в базах данных и не требует включения сложных подпрограмм, то для сборки его страничек Вы вполне можете использовать старый добрый SSI :).

P.S. Разрешается свободно копировать и цитировать данную статью при условии указания открытой активной ссылки на источник и сохранения авторства Руслана Тертышного.

P.P.S. Если Вы никак не решитесь, какой именно язык выбрать для создания сайта, можете почитать следующую статью:

https://www.bestfree.ru/article/webdesign/language.php

Are You Using The WordPress Block Editor?

Genesis now offers plugins that help you build better sites faster with the WordPress block editor (Gutenberg). Try the feature-rich free versions of each plugin for yourself!

Genesis Blocks
Genesis Custom Blocks

Welcome!

These forums are for general discussion on WordPress and Genesis. Official support for StudioPress themes is offered exclusively at My StudioPress. Responses in this forum are not guaranteed. Please note that this forum will require a new username, separate from the one used for My.StudioPress.

This topic is: not resolved

  • This topic has 2 replies, 2 voices, and was last updated 8 years, 5 months ago by AVTsteve.

Viewing 3 posts — 1 through 3 (of 3 total)

  • Author

    Posts

  • September 8, 2014 at 8:00 am

    #123360

    I have a paid real estate plugin called dsIDXpress and i am getting the following error, «Juicebox Error: Config XML file not found.»
    An example of a page where this error occurs

    I have gone back and forth with the plugin provider and they say the problem is with a conflicting plugin, file permissions, or my theme. I have ruled out conflicting plugin by deactivating every plugin except dsIDXpress and the problem persisted. Then they told me that something in my setup was not allowing their software to access a file called client-assist.php so i relaxed permissions as follows to 755:
    wp-content
    plugins
    dsIDXpress
    client assist

    The problem still persists even with every other plugin turned off. Any ideas?

    I’m running WordPress 3.9.2 running AgentPress Two theme.

    http://barbarawatts.com/idx/mls-3030525-5699_morris_hunt_drive_fort_mill_sc_29708

    September 8, 2014 at 2:32 pm

    #123475

    One way to rule out the theme is to switch to the default WordPress theme. Have you done that? If not, switch to one of the default and see if it still happens.


    Love coffee, chocolate and my Bella!

    September 12, 2014 at 2:33 pm

    #124159

    I figured out the problem. My .htaccess in wp-content had the following code:

    <Files *.php>
    deny from all
    </Files>

    When i took out the code, it worked fine. Do you know if there is a «deny from all except» way to allow access to one php file, but not the rest? Thanks!

  • Author

    Posts

Viewing 3 posts — 1 through 3 (of 3 total)

  • The forum ‘General Discussion’ is closed to new topics and replies.

Понравилась статья? Поделить с друзьями:
  • Jsx expressions must have one parent element как исправить
  • Just error кто это
  • Jspdf pubsub error no unicode cmap for font error no unicode cmap for font
  • Just error кардер
  • Just error team