Галерея изображения – Evogallery. Установка и настройка SimpleGallery для MODx EVO Modx evo получение данных из таблицы evogallery

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

Прежде чем приступить к созданию галереи для сайта на движке MODx, нам потребуется скачать сам модуль Evogallery и установить его. Для этого:

  • создадим папку «galleries» в папке «/assets» («/assets/galleries/»);
  • установите права «777» для этой папке;
  • распакуйте скачанный архив;
  • скопируйте содержимое архива «assets/modules/evogallery/» в папку «assets/modules/» вашего сайта;
  • аналогично скопируйте содержимое архива «assets/sneppets/evogallery/» в папку «assets/snippets/» вашего сайта;
  • скопируйте содержимое архива папку «install» в корень сайта;
  • запустите установщик modx для этого наберите в браузере «http://ваш_сайт/install/index.php»;
  • следуйте всем шагам установки, они очень просты;
  • проверьте, чтобы в корне не осталось папки «install», иначе удалите ее.
Добавляем изображения для галереи.

Для того, чтобы добавить изображения необходимо перейти на вкладку «Модули» и выбрать модуль «EvoGallery». Помимо изображений там можно задать названия и описания для изображений.

Вывод галереи MODx на странице.

Теперь нам остается только вывести нашу галерею. Для этого на странице где должна отображаться галерея указываем вызов сниппета:

Чтобы изменить отображение галереи необходимо поправить содержимое файла tpl.item.default.txt, который находится в папке «/assets/snippets/evogallery/simple-list». Этот файл отвечает за отображение фотографии в галереи.

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

Если у вас появятся вопросы, или что-то не получится, напишите в комментариях.

EvoGallery is a dynamic gallery extra for Evo. It allows you to quickly and easily create galleries of images by associating them with any page on your site. Galleries can be outputted in a variety of ways using a templated system.

EvoGallery does not create stand-alone, self-contained galleries that are not associated with a particular page. Every photo uploaded must be associated with a page in the site tree.

History

EvoGallery was originally written by Brian Stanback some years ago and was simply known as the Gallery Module. Jeff Whitfield later took it and rewrote all the javascript using jQuery and used the Uploadify jQuery plugin in an effort to make the uploader compatible with newer versions of Flash.

Many updates have been made since then to give it more functionality.

The name was changed later to EvoGallery in order to differentiate this add-on from many of the other "gallery" add-ons. In January 2011, development has been picked up by several community members with the intention to bring this plugin back to speed.

Install

To install EvoGallery, unzip the downloaded file and follow the following steps:

    Create a directory called "galleries" in the assets directory of your Evo site and give it full write permissions (777).

    Copy / Upload the "assets/modules/evogallery" directory to the "assets/modules" directory of your Evo site.

    Copy / Upload the "assets/snippets/evogallery" directory to the "assets/evosnippets" directory of your Evo site.

    (Optional) Copy / Upload the "assets/plugins/managermanager/functions/gallerylink.inc.php" file to the "assets/plugins/managermanager/functions" directory of your Evo site.

    Copy / Upload the install directory to the root directory of your Evo site

    Run the installer (http://yoursite/install/index.php) and follow the simple on-screen instructions to complete the installation.

Once you"ve completed the installation, be sure and remove the installer directory from your site.

Usage

EvoGallery requires the use of both a module and a snippet to achieve full functionality.

Module

The EvoGallery module allows you to manage all the photos that are associated with the various pages of your site. After clicking on the EvoGallery item under Modules, you"ll be presented with a top-level list of pages from the site tree:

From there, simply click on the links to drill down to the page you wish to manage:

Uploading photos is as easy as clicking on the Select Files button and choosing the photos you want to upload. The files you select will be added to the queue:

To upload the photos, simply click on the Upload Files link below the queue. Each photo will then be uploaded and, along with each photo, a thumbnail will be created. Both photos and thumbnails are processed and resized based on the module configuration (more on that in a second):

Once a photo is uploaded, you can manage the additional properties of the image simply by hovering over an image and clicking on the edit icon. A lightbox will popup that will allow you to update the title, description, and keywords for the image as well as the ability to upload and replace the existing image with a new one:

If you need to delete an image, simply hover over the thumbnail of an image and click on the red "X". You can also reorder the order of the images simply by dragging and dropping images in the order you want and then clicking on the "Save Order" button.

Configuration

Advanced configuration options are available through module configuration:

Name Description Default Value
PHPThumb config for images in JSON (phpthumbImage) PHPThumb parameters for images (see below for details) {"w": 940, "h": 940, "q": 95}
PHPThumb config for thumbs in JSON (phpthumbThumb) PHPThumb parameters for thumbnails (see below for details) {"w": 175, "h": 175, "q": 75}
Root Document ID (docId) ID of the document root to begin listing galleries for (0 for all documents) 0
Save path (savePath) Full system path to location of product images assets/galleries
Module path (modulePath) Path to the module directory assets/modules/evogallery/
Keep original images (keepOriginal) If set to "Yes", this will keep original images when upload Yes
Random filenames (randomFilenames) If set to "Yes", this will apply generated random filenames to uploaded pictures No

Please note the following:

  • PHPThumb config only affect images uploaded AFTER changing the settings. Or you can regenerate all images from action menu.
  • Evo doesn"t support double quotes in parameter values, so use single quote.
  • Some examples of PHPThumb config

    Max width 940, max height 940, quality 95

    {"w": 940, "h": 940, "q": 95}

    Max width 1280, max height 1024, quality 95, apply watermark filter with filename "/assets/images/watermark.png" and position top-left

    {"w": 1280, "h": 1024, "q": 95, "fltr": ["wmi|/assets/images/watermark.png|TL"]}

    Max width 1280, max height 1024, quality 95, zoom crop, apply brightness filter with value 200, apply watermark filter with filename "/assets/images/watermark.png" and position to bottom-right

    {"w": 1280, "h": 1024, "q": 95, "zc": 1, "fltr": ["brit|200", "wmi|/assets/images/watermark.png|BR"]}

    Snippet

    Once you"ve added images to some pages, you then have to output the various images and galleries to the front-end of the site. The EvoGallery snippet allows you to generate lists of your images and galleries in a variety of ways.

    Display

    EvoGallery has three basic display modes when calling the snippet:

    • galleries
    • images
    • single

    The "galleries" mode allows you to display a list of available galleries in a container. By default, the document ID is set to the current document but can be overridden using the "docId" property.

    The "images" mode allows you to display a list of images associated with a given page. By default, the document ID is set to the current document but, just like the "galleries" mode, it can be overridden using the "docId" property.

    The "single" mode allows you to display a single image provided that you know the ID of it in the database. Generally, this information is determined through a separate snippet instance in "images" mode before passing it on to another instance. By default, this mode looks for a "picId" variable via a standard PHP request variable.

    Types

    The "type" property tells the snippet what default templates to use when outputting the list of images or galleries. If you look in the EvoGallery snippet directory (/assets/snippets/evogallery/), you notice that there is a classes folder as well as a few other folders (jquery-cycle, simple-list, and single). These correspond to the available types that can be assigned to the snippet.

    If you look inside a type folder, you"ll notice three files: tpl.config.txt, tpl.default.txt, and tpl.item.default.txt. These files are used to set the default templates for the given type. Other files could be used to set the default templates for the first, last, and alternate items (tpl.item.first.txt, tpl.item.last.txt, and tpl.item.alt.txt respectively).

    The tpl.config.txt file allows you to set which CSS and script files to load when the gallery is called. To add a file, simply create a new line after one of the three designated file type areas: @EXTSCRIPT, @SCRIPT, or @CSS. @EXTSCRIPT is for scripts that are meant to be loaded outside of the given type directly.

    This allows you to load script files using either a direct URL or a path that"s root relative to your site. @SCRIPT is for script files that reside inside the given type directory. @CSS is for CSS files that reside inside the given type directory. If you create subdirectories within the type directory, be sure that the paths written for lines in the @SCRIPT and @CSS sections are relative to your root type directory.

    While you may use a custom type to assign templates to the EvoGallery snippet, it"s not always necessary to do so. You could leave the "type" property out and simply assign chunks to the various templates. Since the default type doesn"t have any CSS or script files assigned for the tpl.config.txt, you"re free to create a snippet call made up of entirely assigned chunk templates.

    Other Properties Name Description Default Value
    display Have the snippet output either a list of galleries within the specified doc Id, a list of images within a gallery, or a single image based on a pic Id. Possible values: galleries, images, single images
    type Output type, if specified, the snippet will automatically load the required javascript. Pre-packaged types: simple-list, single, jquery-cycle simple-list
    includeAssets Register external scripts and CSS files required by the specified gallery type. If set to 0, these will need to be included manually in the document 1
    picId ID of specific pic to show when displaying by a single image $_REQUEST[ "picId" ]
    docId Document ID for which to display gallery (default: document from which snippet was called). Multiple document id"s can be specified by commas (no spaces), or * for all documents $modx->documentIdentifier
    gallerySortBy Galleries sort order (possible fields: id, pagetitle, longtitle, description, alias, pub_date, introtext, editedby, editedon, publishedon, publishedby, menutitle) or RAND() menuindex
    gallerySortDir Direction to sort the galleries ASC or DESC ASC
    ignoreHidden Display documents marked as hidden in the gallery listing 0
    excludeDocs Prevent the specified documents from showing in the gallery listing. Multiple document id"s can be specified by commas (no spaces). 0
    sortBy Sort items by field (possible fields: id, content_id, filename, title, description, sortorder) or RAND() sortorder
    sortDir Direction to sort the items ASC or DESC ASC
    limit Limit the number of items to display null
    tags Comma delimited set of tags to filter results by. Looks in the keywords field for the images. null
    tagMode Search mode for tag: AND or OR AND
    tpl Chunk template for the outer gallery template (defaults to tpl.default.txt for selected type). Placeholders: items $this->config["snippetPath"] . $this->config["type"] . "/tpl.default.txt"
    itemTpl Chunk template for each thumbnail/image in the gallery. See below for available placeholders. $this->config["snippetPath"] . $this->config["type"] . "/tpl.item.default.txt"
    itemTplFirst Chunk template for last thumbnail/image in the gallery (defaults to tpl.item.first.txt for selected type) $this->config["snippetPath"] . $this->config["type"] . "/tpl.item.first.txt"
    itemTplLast Chunk template for last thumbnail/image in the gallery (defaults to tpl.item.last.txt for selected type) $this->config["snippetPath"] . $this->config["type"] . "/tpl.item.last.txt"
    itemTplAlt Chunk template for alternate thumbnail/image in the gallery (defaults to tpl.item.alt.txt for selected type) $this->config["snippetPath"] . $this->config["type"] . "/tpl.item.alt.txt"
    itemAltNum Modifier for the alternate thumbnail/image (defaults to every second item) 2
    galleriesUrl URL to the galleries directory (should contain folders with the Id of the document, with a thumbs/ folder within each document"s gallery) $modx->config[ "base_url" ] . "assets/galleries/"
    galleriesPath Path to the galleries directory $modx->config[ "base_path" ] . "assets/galleries/"
    snippetUrl URL to the snippet directory $modx->config[ "base_url" ] . "assets/snippets/evogallery/"
    snippetPath Path to the snippet directory $modx->config[ "base_path" ] . "assets/snippets/evogallery/"
    id Unique ID for this EvoGallery instance and unique URL parameters null
    paginate Paginate the results set into pages of &show length 0
    paginateAlwaysShowLinks Determine whether or not to always show previous next links 0
    show Number of images to display in the results when pagination on 20
    paginateNextText Text for next label Next
    paginatePreviousText Text for previous label Previous
    tplPaginatePrevious Template for the previous link
    tplPaginateNext Template for the next link
    tplPaginateNextOff Template for the inside of the next link
    tplPaginatePreviousOff Template for the inside of the previous link
    tplPaginatePage Template for the page link
    tplPaginateCurrentPage Template for the current page link
    Examples

    Output a list of images using the jQuery Cycle type (jquery-cycle):

    []

    Output a list of images using the jQuery Cycle type (jquery-cycle), sorted on the "sortorder" variable:

    []

    Output the galleries available in a specific container using a specific item template:

    []

    Template Placeholders

    Depending on the display type, there are several available placeholders which you may use in the chunks for the template parameters. You can also reference a template variable by its name. These placeholders have PHx enabled, so you may use specific PHx syntax in your templates.

    Placeholder Available in Outputs
    total Gallery display Total amount of images within the current gallery.
    images_dir Image directory for the current gallery.
    thumbs_dir Gallery, single and images display Thumbnail directory for the current gallery.
    original_dir Gallery, single and images display Original image directory for current gallery.
    plugin_dir Gallery, single and images display URL path of current output type
    id Gallery, single and images display In gallery display, this returns the document ID for the current gallery. In images and single view, this returns the unique ID (picId) for an image.
    content_id Single and images display Returns the document ID the image is linked to.
    filename Gallery, single and images display The filename of the current image. In Gallery view, this is the first image of the gallery based on the sortBy and sortOrder parameters.
    title Single and images display Title which has been specified in the backend.
    description Single and images display Description which has been specified in the backend.
    keywords Single and images display Comma delimited list of keywords for the image as specified in the backend.
    sortorder Single and images display Sort number, based on the order in the backend
    Resource variables Gallery display The following resource variables are available in gallery display through placeholders:
    id, pagetitle, longtitle, description, alias, pub_date, introtext, editedby, editedon, publishedon, publishedby, menutitle
    ManagerManager Function

    Included in the distribution of EvoGallery is an optional function for the ManagerManager plugin that allows you to create a link directly to the section of EvoGallery that is related to a given page. This is a great help to content editors since they don"t have to constantly click over to the EvoGallery module and drill down to manage the page they want.

    To use the function, simply create a text template variable and name it whatever you want. Next, add the following call to your ManagerManager rules:

    Mm_galleryLink($fields, $roles, $templates, $moduleid);

    • $fields should be replaced with the field name you want to affect. If you named your template variable "gallery" you replace $fields with "gallery".

    Since EvoGallery 1.1 in the distribution is an optional widget for the ManagerManager plugin that allows you to create a tab within document editing page

    Mm_widget_evogallery($moduleid, $title, $roles, $templates);

    • $moduleid is a custom variable specific to this function. It tells the function what module ID to use. To find out the ID of a module, simply copy the link to the module in the main menu. The ID will be part of the URL itself. E.g.: /manager/index.php?a=112&id=2. In this case, the $moduleid is 2.
    • $title is display name of tab.
    • $roles should be replaced with the IDs of the roles that should be affected or left empty to apply the rule to all roles.
    • $templates contains the IDs of templates to apply the rule to, or can be left empty to apply to all templates.

    Источник: http://cstudiopro.ru/sozd-site/cms/modx-cms/sozdaem-sajt-urok14.php

    EvoGallery - позволяет создавать галерею изображений на MODx Evolution.

    Пример реализации EvoGallery можно посмотреть на странице Evo_Gallery .

    Фотогалерея включает три альбома, которые выводятся на страницу Evo_Gallery . Т.е. для ресурса Evo_Gallery надо создать три дочерних ресурса Альбом 1, Альбом 2, Альбом 3 . См. рисунок 1.

    Рисунок 1

    При нажатии на миниатюру, появляется увеличенное изображение средствами скрипта FancyBox . Поэтому нам понадобится еще этот скрипт.

    Инструкция по созданию такой галереи

    1. Сначала скачиваем дистрибутив EvoGallery .

    2. В архиве две папки: «assets» и «install». Архив надо распаковать на сервер в папку www , при распаковке подтвердить слияние папок.

    Появится установка модуля MODx Gallery, которая включает следующие этапы:

    • выбор языка. Русский;
    • выбор параметров. Оставляете так, как есть (модуль, плагин и сниппет);
    • проверка перед установкой. Соглашаемся с лицензией, жмем кнопку «Дальше»;
    • результаты установки. Обратите внимание на пункт «Удалить папку и файлы программы установки с моего сайта». Обязательно олжна стоять галочка;
    • установка завершена. Жмем «Закрыть», и входим в панель администратора, введя логин и пароль.

    4. Скачиваем архив скрипта FansyBox . И распаковываем в папку assets / js / gallery /. См. рисунок ниже.

    Рисунок 2

    5. Создаем отдельный шаблон evo_gallery . В этом шаблоне в (или перед закрывающим ) вставляем следующий код:





    $(document).ready(function() {
    $(".fancybox").fancybox({
    openEffect: "none",
    closeEffect: "none"});
    });

    6. Создаем ресурс Evo_Gallery с шаблоном evo_gallery , на страницу которого будут выводиться фотоальбомы. Описания для ресурса могут быть такими (рис. 3).

    На странице Evo_Gallery вставляем вызов сниппета EvoGallery:

    Здесь использованы следующие параметры:

    • &docId=`240` - id страницы, дочерние ресурсы которого являются альбомами, вставьте сюда свой id;
    • &display=`galleries` - категория вывода, возможные значения: galleries, images, single;
    • &itemTpl=`item-list` - шаблон вывода информации об альбоме.

    Рисунок 3

    8. Создаем чанк item - list с кодом:



    [+longtitle+]

    [+introtext+]


    [+pagetitle+]

    9. Создаем три дочерних ресурса Альбом 1, Альбом 2, Альбом 3 с шаблоном evo_gallery . В содержимое каждого ресурса вставляем код:

    [*introtext*]


    []

    Рисунок 4

    10. В папке simple-list , находящийся по адресу: assets/snippets/evogallery/simple-list , есть файл tpl.item.default. txt , отвечающий за шаблон вывода одной фотографии. Нужно удалить содержимое файла, и вставить в него следующий код:

    11. В шаблоне evo_gallery в вставляем таблицу стилей:


    /* Галерея */
    .img-all .img-gallery {width:200px; height:160px; margin:0 15px 25px 0; padding:5px;}
    .img-all img {width: 195px; height: 155px;}
    .img-gallery {float:left;}
    .albom-gallery {clear:both; padding-bottom: 30px; padding-top: 10px;}
    .albom-gallery img {float:left; padding:5px; border:1px solid #CCC; margin-right:20px; width: 170px; height: 126px;}
    .albom-gallery span a {font-size:18px; font-family: Georgia, "Times New Roman", Times, serif; color: #777 ;}
    .albom-gallery span a:hover {color:#999;}

    12. Сейчас надо загрузить фотографии в наши альбомы. Скачиваем архив для альбомов .

    Заходим в административную панель, и переходим по ссылке в меню: Модули - EvoGallery .

    Кликаем по «Evo_Gallery» , потом «Альбом 1» . Кликаем по кнопке « Select Files », появляется окно выбора изображений. Из распакованных файлов находим папку «Альбом 1». Выделяем все и нажимаем кнопку «Открыть».


    Рисунок 5

    Если возникает ошибка с сообщением, что файл большой, следует изменить максимальный размер загрузки файла. Для этого идем по вкладкам Инструменты - Конфигурация - Максимальный размер загрузки , и устанавливаем значение в байтах, например 20000000.

    Если это не помогает, то попробуйте прописать в.htaccess следующее:

    php_value upload_max_filesize 20M
    php_value post_max_size 20M
    php_value max_execution_time 100

    Это увеличит размер закачки до 20Мб, а время исполнения до 100 секунд.

    Предупреждение!!!
    Данный модуль фотогалереи EvoGallery имеет уязвимость, позволяющую загрузить произвольный файл (в том числе и хакерский шелл).
    Поэтому после установки галереи удалите файл uploadify.php по адресу /assets/modules/evogallery/js/uploadify/uploadify.php

    Скажу сразу, что данная статья предназначена для новичков.

    Итак, что нам нужно, для того чтобы быстро вывести фотогалерею на странице?

    1) Установите из репозитория модуль (я использую сборку от Dmi3yy). Репозиторий находится в Модули - Extras.

    2) В чанке mm_rules пропишите строку
    mm_widget_evogallery(4, Галерея, "1,2,3", 6);
    где
    4 - это id модуля, его можно посмотреть наведя мышь на название модуля
    Галерея - это название таба, тут можно писать что угодно
    1,2,3 - это указание того, кто будет видеть этот таб (можно посмотреть в «Роли пользователя»)
    6 - это id шаблона, к которому будет прикреплена галерея

    3) Теперь выведем галерею на странице сайта. Для этого в шаблоне страницы выведем следующий код:
    []
    и создадим чанк simple-list-tpl :

    4) Не забудьте установить библиотеку Fancybox из репозитория. Она нужна, чтобы открывать увеличенные фотографии в модальном окне. Но в принципе, вы можете использовать любую библиотеку, на ваше усмотрение.
    Чанк с именем fancybox, вставьте в шаблон страницы, не забыв подключить JQuery.

    $(document).ready(function() { $(".fancybox").fancybox(); });

    5) Подправим CSS стили, чтобы добавить немного красоты.

    Photo a img { padding:5px 5px 5px 5px; background-color:#FFFFFF; border:#ccc 1px solid; margin:5px 10px 5px 0;}