Jump to content
BitPoet

Module: MediaLibrary

Recommended Posts

MediaLibrary

Update: MediaLibrary can now be found in the official module list.

Out of necessity, I've started to implement a simple media library module.

The basic mechanism is that it adds a MediaLibrary template with file and image fields. Pages of this type can be added anywhere in the page tree.

The link and image pickers in CKEditor are extended to allow quick selection of library pages from dropdowns. In the link picker this happens in the MediaLibrary tab, where you can also see a preview of the selected image. In the image picker, simply select a library from the dropdown at the top, everything else is handled by standard functionality.

I've put the code onto github. This module is compatible with ProcessWire 3.

Steps to usage:

  • Download the module's zip from github (switch to the pw3 branche beforehand if you want to test on PW 3.x) and unpack it into site/modules
  • Click "Modules" -> "Refresh" in the admin
  • Click "Install" for MediaLibrary
  • For testing, create a page with the MediaLibrary template under home (give it an expressive title like 'Global Media') and add some images and files
  • Edit a differnt page with a CKEditor field and add a link and an image to see the MediaLibrary features in action (see the screencap for details)
  • Optionally, go into the module settings for MediaLibrary

Note: this module is far from being as elaborate as Kongondo's Media Manager (and doesn't plan to be). If you need a feature-rich solution for integrated media management, give it a look.

Feel free to change the settings for MediaFiles and MediaImages fields, just keep the type as multiple.

There are some not-so-pretty hacks for creating and inserting the correct markup, which could probably be changed to use standard input fields, though I'm a bit at a loss right now how to get it to work. I've also still got to take a look at error handling before I can call it fit for production. All feedback and pointers are appreciated (that's also why I post this in the development section).

post-2900-0-51982400-1457341364_thumb.gi

Edit 09.03.2016 / version 0.0.4: there's now also a "Media" admin page with a shortcut to quickly add a new library.

post-2900-0-71225900-1457553239_thumb.pn

Edit 01.05.2016:

Version 0.0.8:

- The module now supports nested media libraries (all descendants of eligible media libraries are also selectable in link/image picker).

- There's a MediaLibrary::getPageMediaLibraries method you can hook after to modify the array of available libraries.

- You can switch between (default) select dropdowns or radio boxes in the module configuration of MediaLIbrary to choose libraries.

Edit 10.10.2018:

Version 0.1.3:

- Dropped compatibility for ProcessWire legacy versions by adding namespaces

- Allow deletion of libraries from the Media overview admin page

- Added an option to hide media libraries from the page tree (optionally also for superusers)

  • Like 23

Share this post


Link to post
Share on other sites

That looks really great and is certainly a quick and easy solution for websites, which need a overseeable amount of globally shared assets.

Share this post


Link to post
Share on other sites

Yes, many site owners welcome easy link/picture/doc updating like this.

Share this post


Link to post
Share on other sites

My primary application will be for our intranet site where we have complex product datasheets and configuration information that link to parts sheets, supplier information, technical standards and whatnot. Keeping linked documents up-to-date is quite important, and with today's innovation speed we've got about twenty to thirty doc updates per workday. I'll probably keep creation rights for the MediaLibrary template limit to admins though, to avoid over-eager users cluttering every page with a media child (just in case...).

  • Like 4

Share this post


Link to post
Share on other sites

How about prepopulating a library (from Select library) if there is only one? Or some kind default library? How does it scale with a lot of images, like 1000?

Share this post


Link to post
Share on other sites

Hello,

"Only libraries under the edited page itself or one of its parents are available to keep things organized."

So, it means it can be under a direct parent (it will be a sibling of the edited page) or a child of the page itself, is that it?

Also, as we can already, with ProcessWire by default, create a "Media Library" page anywhere, put images and files in it, and create sub-pages ("sub-sections", "sub-folders", "sub-categories"...) with images and files in it also, and already select them via CKEditor, would it be "difficult" to also have a "Media Library" tab (the "Media Library" page(s) (and/or template(s)) would be defined in a configuration page, etc.) and a way to (drop-down) select the "Media Library" page/"root" or one of its children in order to have only the images and files from a specific (sub-)section?

(And perhaps a way to have only images or only files. But that could wait.)

It's "already there"*, it's just that we only see, for example, the image thumbnails. Perhaps, for example, a "list mode" button in order to see the image names and/or descriptions could be added. (I'll have to check again how it is if they are files and not images).

It's also that it can take quite some time sometimes to find/go to the "Media Library"/"root" page in this case*, so a way to have direct access to it via a tab, after having defined it(/them) would be nice.

This module is a nice addition, it's just that I've been wondering this for some time.

I've done it with a "root" page and sub-pages with one image/page (logos, etc.) and have realized (again) that it could also be simply done with several images/page where sub-pages would be (sub-)categories.

Share this post


Link to post
Share on other sites

How about prepopulating a library (from Select library) if there is only one? Or some kind default library? How does it scale with a lot of images, like 1000?

I don't want to dig too deeply into circumventing PW's default behavior, so doing things in steps is the way to go for me. This way, I can use PW's default behavior in a lot of places. As for lots of images, it's the same as if they were added to the page itself, so with enough images the pwimage dialog will get sluggish (when depends on the client machine). While it doesn't scale infinitely, it should work in most common scenarios. The file links scale better performance wise, as only one is previewed at a time, though there's definitely a limit too when editing the library pages themselves.

Hello,

"Only libraries under the edited page itself or one of its parents are available to keep things organized."

So, it means it can be under a direct parent (it will be a sibling of the edited page) or a child of the page itself, is that it?

Also, as we can already, with ProcessWire by default, create a "Media Library" page anywhere, put images and files in it, and create sub-pages ("sub-sections", "sub-folders", "sub-categories"...) with images and files in it also, and already select them via CKEditor, would it be "difficult" to also have a Media Library tab (the "Media Library" page would be defined in a configuration page, etc.) and a way to (drop-down) select the "Media Library page/"root" or one of its children in order to have only the images and files from a specific (sub-)section.

(And perhaps a way to have only images or only files. But that could wait.)

It can be a sub page of any ancestor, so a child of a "grandparent" or higher up works too.

I'll probably not add much functionality besides what is already there in the short run. I see where you're heading, but that would be counter-productive to what I'm trying to accomplish (at least, where I'm planning to use it). I'll keep the idea in mind, and I won't rule out implementing it if a short, clean solution jumps my mind, but I've got too many other things already on the backburner. If you or somebody else uses my code to as a building block for something like this, you're welcome though.

  • Like 1

Share this post


Link to post
Share on other sites

"It can be a sub page of any ancestor, so a child of a "grandparent" or higher up works too."

So it can be a direct child of the homepage (I was wondering while reading the sentence on github).

But there could be too many images to choose from...

Your module has a lot of use cases.

I'll have to improve my (beginner) coding skills first :). (I'm starting with JUMP START PHP ENVIRONMENT now.)

Share this post


Link to post
Share on other sites

Yes, there's obviously a danger to add too many files to a library and make things convoluted. There's a point where simple dropdowns aren't practical anymore, but then, structuring information always is an ongoing task. That's a reason why one of the next points on my todo-list at work is a small module to show file usage (i.e. which pages' html fields link to a given pagefile), though that's probably going to be less pratical as I'll use a custom link and image url extractor in our OpenSearchServer to get quick results and avoid parsing multiple fields in a few thousand pages in the database for every file.

I haven't read that book, but getting acquainted with tool sets and release procedures before forming bad habits sounds like a good plan, even if not everything (like e.g. composer use) can be used for every project. It's often harder to un-learn a bad habit than learn it the right way first. :)

  • Like 3

Share this post


Link to post
Share on other sites

Update: I've added a "Media" admin page with a quick create option for new library pages.

  • Like 6

Share this post


Link to post
Share on other sites

It could be good to upload images to the media library in ckeditor.

Current, it may confused users, uploaded a image in ckeditor of a editing page, but it could not show up on other pages.

Share this post


Link to post
Share on other sites

It already does that - or, to be more precise, PW's default behavior takes care of that.

post-2900-0-07449400-1457845208_thumb.gi

  • Like 5

Share this post


Link to post
Share on other sites

Thanks for this great module. When using the option to upload images with the media library in CKeditor (like you've mentioned in the previous post). Everything seems to be working fine. However when I visit the page the next day, the image is gone and it's also removed from the Mediamanager.

However when uploading an image directly to the MediaManager (through the link in the sidebar) the images will be there the next day.

Do you have an idea what's causing this?

Share this post


Link to post
Share on other sites

That's strange. Could you do a few checks to narrow it down? Is the uploaded image present in the file system under site/assets/id of the media library page? Is the image tag in the output still present and if yes, what does it look like? Also, which PW version are you using?

Share this post


Link to post
Share on other sites

I've tested it in a bit more detail:
- The uploaded image isn't present under site/assets/id. Both the original and the thumbnail image are gone

- The image tag in the output is still present. It looks like <img alt="" src="/site/assets/files/[id]/[image].jpg" width="800">

- I'm currently using ProcessWire 3.0.11

If you need any additional information, please let me know.

Share this post


Link to post
Share on other sites

I installed 3.0.11 and tested it, and here it worked, but there are so many different parameters that might interfere. So, just to be sure:

  • You edit a page in CKEditor and select a media library from there, then upload an image (let's call it 'test.png')
  • After that, PW should place the image and thumbnails in "site/assets/files/[iD of media library page]/".
  • Can you confirm that the id CKEditor puts into the image tag is the id of the media library page you selected?
  • Is the image there on the file system immediately after you upload it?

If I recall it right, there were some issues with image uploading in certain settings when always_populate_raw_post_data was enabled, but I'm not sure if that still applies. Also, memory limits in php.ini might be worth a look. Generally, though, if you can upload images and get a preview, everything should be running fine. Do you have any other site modules installed?

Share this post


Link to post
Share on other sites

Thanks for checking it out. Uploading images isn't the problem. At first the image is being added to the page correctly and everything is working. The problem arises the next day (I have the feeling it happens somewhere through the night) when the image is being removed. This only happens when uploading the image through CKEditor. When uploading images through the 'Media' page in the sidebar, the images aren't removed automatically.

You edit a page in CKEditor and select a media library from there, then upload an image (let's call it 'test.png')

Yes indeed.

After that, PW should place the image and thumbnails in "site/assets/files/[iD of media library page]/".

That's indeed also the case. The image is added to the assets/files/[id of media library page] folder.

Can you confirm that the id CKEditor puts into the image tag is the id of the media library page you selected?

Yes, that's also the case. In the page the id is used from the media library.

Is the image there on the file system immediately after you upload it?

The image is there after I uploaded it. There are two images (the original file and a thumbnail version).

Do you have any other site modules installed?

On the website, the following modules have been installed:

- ProCache

- Form Builder

- Profields (Table)

- MarkupSEO

- MarkupSimpleNavigation

- TextformatterGoogleMaps

- TextformatterVideoEmbed

- TextformatterSrcSet (but it's not enabled inside the body field where the images disappear)

To be safe, i've added a screenshot of the settings that i've used for the body field. Might the 'HTML Options' have something to do with it?

be64ab.png

If you want I can give you temporarily access to the website.

Share this post


Link to post
Share on other sites

Just curious, I have everything set up and a new "gallery" set up using the library, but how do you actually utilize it in a template?

Share this post


Link to post
Share on other sites

It's not really designed to be used in a template through the API, the use case was to make re-using images and documents in CKEditor less complicated. Behind the scene, MediaLibraries are nothing but pages with a MediaImages and MediaFiles field, the magic is the concise overview over dedicated media pages (and their creation without navigating through the page tree) and, most importantly, the quick selection in the CKEditor dialogs.

You can get the available libraries for a page through the API though:

/* Retrieve all available MediaLibraries for the current page */

// get possible parents first
$mparents = $page->parents->and($page);

// get PageArray with all possible libraries
$libs = $pages->find("template=MediaLibrary, parent=$mparents");

// do something with libraries
foreach($libs as $lib) {
    echo $lib->title . PHP_EOL;
    // Every library is just a page with the fields MediaImages and MediaFiles
    foreach($lib->MediaImages as $img) {
        echo "<img src='$img->url'/><br/>" . PHP_EOL;
    }
}

Of course, you can fetch a specific library through regular selector syntax too, e.g.:

$lib = $pages->get("template=MediaLibrary, name=global-media");

foreach($lib->MediaFiles as $file) {
 // ...
}
  • Like 3

Share this post


Link to post
Share on other sites

It's almost perfect for the task I would use it, but am I right that I need to create multiple Media Libraries under Home to have multiple "categories" of libraries? I tried to put them under a page not to pollute the root with many Media Libraries but then they don't show up in the selector when trying to insert an image.

Update:

I see it's possible to use it from subpages but my current multi-user setup doesn't allow placing them in ancestor pages. 

I wanted something like this:

- global page
- global page
- global page
- user page
- - user subpage
- - user subpage
- user page
- - user subpage
- - user subpage
- Media Library parent page
- - Library 1
- - Library 2

So users cannot reach Library 1 in this setup.

Share this post


Link to post
Share on other sites

I'm a little bit uncomfortable with allowing just any child under a media library, but I can understand the wish for nesting, so version 0.0.7 on github allows you to create libraries under existing MediaLibrary pages, and these child libraries (no limit for nesting) are also listed whenever their parent library is.

For anybody planning to use MediaLibrary through the API, there's a new method that returns an array with all applicable media pages for a given page (following the under-parent-or-current-page rule):

$ml = wire('modules')->get('MediaLibrary');
$mediapages = $ml->getPageMediaLibraries($page);

foreach($mediapages as $mpage) {
   // ...
}

I've made getPageMediaLibraries hookable if anybody wants to apply further rules to which pages should be available.

  • Like 2

Share this post


Link to post
Share on other sites

Thanks! Setting "/medialibrary1/medialibrary2" allows users selecting images from these pages now.

I didn't wanted them to see or use images from "/medialibrary1" but it's something I can live with :)

Now I can use it for common site-wide images, which will be a great plus.

Have you considered changing the way Media Libraries are selected? The current selectbox doesn't seem too user-friendly UI-wise. Maybe radios would be better so they could see libraries with fewer clicks.

  • Like 1

Share this post


Link to post
Share on other sites

Just grab the latest version from git (if you get a message that configurable module test failed, repeatedly refresh modules until the message goes away), then go into the module configuration and select "Radios".

:)

You can exclude certain media pages from showing up for the user through a hook in ready.php:

wire()->addHookAfter("MediaLibrary::getPageMediaLibraries", null, "filterLibraries");

function filterLibraries($event) {
  $media = $event->return;
  if(! wire('user')->isSuperUser) {
    $event->return = array_filter($media, function($v) {
      return ($v->id != $ID_OF_PAGE_TO_EXCLUDE);
    });
  }
}
  • Like 3

Share this post


Link to post
Share on other sites

Great, thanks! Both working fine.

However, when going to the Media page in the admin, I get an error:

"Call to a member function count() on null"

line:

https://github.com/BitPoet/MediaLibrary/blob/master/ProcessMediaLibraries.module#L41

I've removed the MediaFiles from the template, I guess that's why.

Possible fix:

		foreach($this->pages->find("template=MediaLibrary") as $pg) {

			$MediaImagesCount = $pg->MediaImages ? $pg->MediaImages->count() : 0;
			$MediaFilesCount = $pg->MediaFiles ? $pg->MediaFiles->count() : 0;
			
			$tbl->row(array(
				"<a href='{$pg->editURL}'>{$pg->title}</a>",
				implode(' / ', array_map(function($item) { return "<a href='{$this->config->urls->admin}page/?open=$item->id'>$item->title</a>"; }, $pg->parents()->getArray())),
				$MediaImagesCount,
				$MediaFilesCount
			));
		}
  • Like 1

Share this post


Link to post
Share on other sites
Hi.

Thanks for useful module.

I noticed that MediaLibrary.js is loading on frontend even if there is no edit functionality?

Is it normal behavior?

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      First a note about my other modules...
      I have three existing modules that are similar in that they allow restrictions to be placed on repeating inputfields: Limit Repeater, Limit PageTable, Limit Table
      Restrict Repeater Matrix takes a different approach to the module configuration from those other modules. The module settings for Restrict Repeater Matrix are applied in the field settings rather in a module config screen. I think this new approach is better, but it means that it isn't practical to create different settings for different roles via the admin interface. Instead the module has a hookable method, allowing roles to be targeted and other advanced usages to be achieved via a hook. The result is that the module is more flexible.
      I intend to transition my other modules to the same approach over the coming weeks, but because this will result in breaking changes I will be releasing the updated modules under new names ("Restrict Repeater", etc) to avoid users upgrading via the Upgrades module without full awareness of the changes. The old modules will be marked as deprecated.
      Restrict Repeater Matrix
      A module for ProcessWire CMS/CMF. Allows restrictions and limits to be placed on Repeater Matrix fields. Requires ProcessWire >= v3.0.0 and FieldtypeRepeaterMatrix >= v0.0.5.
      For any matrix type in a Repeater Matrix field you have the option to:
      Disable settings for items (cannot change matrix type) Prevent drag-sorting of items Prevent cloning of items Prevent toggling of the published state of items Prevent trashing of items Limit the number of items that may be added to the inputfield. When the limit is reached the "Add new" button for the matrix type will be removed and the matrix type will not be available for selection in the "Type" dropdown of other matrix items. Please note that restrictions and limits are applied with CSS/JS so should not be considered tamper-proof.
      Usage
      Install the Restrict Repeater Matrix module.
      For each matrix type created in the Repeater Matrix field settings, a "Restrictions" fieldset is added at the bottom of the matrix type settings:

      For newly added matrix types, the settings must be saved first in order for the Restrictions fieldset to appear. Set restrictions for each matrix type as needed. A limit of zero means that no items of that matrix type may be added to the inputfield.
      Setting restrictions via a hook
      Besides setting restrictions in the field settings, you can also apply or modify restrictions by hookingRestrictRepeaterMatrix::checkRestrictions. This allows for more focused restrictions, for example, applying restrictions depending on the template of the page being edited or depending on the role of the user.
      The checkRestrictions() method receives the following arguments:
      $field This Repeater Matrix field $inputfield This Repeater Matrix inputfield $matrix_types An array of matrix types for this field. Each key is the matrix type name and the value is the matrix type integer. $page The page that is open in ProcessPageEdit The method returns a multi-dimensional array of matrix types and restrictions for each of those types. An example of a returned array:

      Example hooks
      Prevent the matrix type "images_block" from being added to "my_matrix_field" in a page with the "basic-page" template:
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $page = $event->arguments('page'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && $page->template->name === 'basic-page') { $type_restrictions['images_block']['limit'] = 0; } $event->return = $type_restrictions; }); Prevent non-superusers from trashing any Repeater Matrix items in "my_matrix_field":
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && !$this->user->isSuperuser()) { foreach($type_restrictions as $key => $value) { $type_restrictions[$key]['notrash'] = true; } } $event->return = $type_restrictions; }); http://modules.processwire.com/modules/restrict-repeater-matrix/
      https://github.com/Toutouwai/RestrictRepeaterMatrix
    • By BitPoet
      Here's a little text formatter module that redirects all external links found in a textarea (e.g. for hit counting) to a given URL.
      TextformatterExternalRedirect
      GitHub repo
      As TextFormatters do, this module modifies the contents of the textarea (HTML) at rendering time. It prepends the given URL to the link address for external links (http and https), optionally makes sure that the link is opened in a new window and allows you to add css classes to such links.
      All options can be configured in the module's configuration settings.
      Usage:
      Download the zip archive and extract it to site/modules, the rename the top folder to TextformatterExternalRedirect Go to the backend and select "Modules" -> "Refresh", then click "Install" for "External Link Redirect" Click "Settings" and configure the module
      Go into the field configuration for the field(s) you want this formatter to apply to and add it from the dropdown
      Done, now any external links in the configured fields will have the configured settings applied Feel free to leave feedback and post and questions you have here.
       
    • By teppo
      Hey folks!
      Took a couple of late nights, but managed to turn this old gist of mine into a proper module. The name is SearchEngine, and currently it provides support for indexing page contents (into a hidden textarea field created automatically), and also includes a helper feature ("Finder") for querying said contents. No fancy features like stemming here yet, but something along those lines might be added later if it seems useful (and if I find a decent implementation to integrate).
      Though the API and selector engine make it really easy to create site search pages, I pretty much always end up duplicating the same features from site to site. Also – since it takes a bit of extra time – it's tempting to skip over some accessibility related things, and leave features like text highlighting out. Overall I think it makes sense to bundle all that into a module, which can then be reused over and over again 🙂
      Note: markup generation is not yet built into the module, which is why the examples below use PageArray::render() method to produce a simple list of results. This will be added later on, as a part of the same module or a separate Markup module. There's also no fancy JS API or anything like that (yet).
      This is an early release, so be kind – I got the find feature working last night (or perhaps this morning), and some final tweaks and updates were made just an hour ago 😅
      GitHub repository: https://github.com/teppokoivula/SearchEngine Modules directory: https://modules.processwire.com/modules/search-engine/ Demo: https://wireframe-framework.com/search/ Usage
      Install SearchEngine module. Note: the module will automatically create an index field install time, so be sure to define a custom field (via site config) before installation if you don't want it to be called "search_index". You can change the field name later as well, but you'll have to update the "index_field" option in site config or module settings (in Admin) after renaming it.
      Add the site search index field to templates you want to make searchable. Use selectors to query values in site search index. Note: you can use any operator for your selectors, you will likely find the '=' and '%=' operators most useful here. You can read more about selector operators from ProcessWire's documentation.
      Options
      By default the module will create a search index field called 'search_index' and store values from Page fields title, headline, summary, and body to said index field when a page is saved. You can modify this behaviour (field name and/or indexed page fields) either via the Module config screen in the PocessWire Admin, or by defining $config->SearchEngine array in your site config file or other applicable location:
      $config->SearchEngine = [ 'index_field' => 'search_index', 'indexed_fields' => [ 'title', 'headline', 'summary', 'body', ], 'prefixes' => [ 'link' => 'link:', ], 'find_args' => [ 'limit' => 25, 'sort' => 'sort', 'operator' => '%=', 'query_param' => null, 'selector_extra' => '', ], ]; You can access the search index field just like any other ProcessWire field with selectors:
      if ($q = $sanitizer->selectorValue($input->get->q)) { $results = $pages->find('search_index%=' . $query_string . ', limit=25'); echo $results->render(); echo $results->renderPager(); } Alternatively you can delegate the find operation to the SearchEngine module as well:
      $query = $modules->get('SearchEngine')->find($input->get->q); echo $query->resultsString; // alias for $query->results->render() echo $query->pager; // alias for $query->results->renderPager() Requirements
      ProcessWire >= 3.0.112 PHP >= 7.1.0 Note: later versions of the module may require Composer, or alternatively some additional features may require installing via Composer. This is still under consideration – so far there's nothing here that would really depend on it, but advanced features like stemming most likely would.
      Installing
      It's the usual thing: download or clone the SearchEngine directory into your /site/modules/ directory and install via Admin. Alternatively you can install SearchEngine with Composer by executing composer require teppokoivula/search-engine in your site directory.
    • By teppo
      MarkupMenu is a markup module for generating menu trees. When provided a root page as a starting point, it generates a navigation tree (by default as a HTML "<ul>" element wrapped by a "<nav>" element) from that point onwards. If you've also provided it with current (active) page, the menu will be rendered accordingly, with current item highlighted and items rendered up to that item and its children (unless you disable the "collapsed" option, in which case the full page tree will be rendered instead).
      Modules directory: https://modules.processwire.com/modules/markup-menu/ GitHub repository: https://github.com/teppokoivula/MarkupMenu Usage
      As a markup module, MarkupMenu is intended for front-end use, but you can of course use it in a module as well. Typically you'll only need the render() method, which takes an array of options as its only argument:
      echo $modules->get('MarkupMenu')->render([ 'root_page' => $pages->get(1), 'current_page' => $page, ]); Note: if you omit root_page, site root page is used by default. If you omit current_page, the menu will be rendered, but current (active) page won't be highlighted etc.
      A slightly more complex example, based on what I'm using on one of my own sites to render a (single-level) top menu:
      echo $modules->get('MarkupMenu')->render([ 'current_page' => $page, 'templates' => [ 'nav' => '<nav class="{classes} menu--{menu_class_modifier}" aria-label="{aria_label}">%s</nav>', 'item_current' => '<a class="menu__item menu__item--current" href="{item.url}" tabindex="0" aria-label="Current page: {item.title}">{item.title}</a>', ], 'placeholders' => [ 'menu_class_modifier' => 'top', 'aria_label' => 'Main navigation', ], 'include' => [ 'root_page' => true, ], 'exclude' => [ 'level_greater_than' => 1, ], ]); Note: some things you see above may not be entirely sensible, such as the use of {menu_class_modifier} and {aria_label} placeholders. On the actual site the "nav" template is defined in site config, so I can define just these parts on a case-by-case basis while actual nav markup is maintained in one place.
      Please check out the README file for available render options. I'd very much prefer not to keep this list up to date in multiple places. Basically there are settings for defining "templates" for different parts of the menu (list, item, etc.), include array for defining rules for including in the menu and exclude array for the opposite effect, classes and placeholders arrays for overriding default classes and injecting custom placeholders, etc. 🙂
      MarkupMenu vs. MarkupSimpleNavigation
      TL;DR: this is another take on the same concept. There are many similarities, but also some differences – especially when it comes to the supported options and syntax. If you're currently using MarkupSimpleNavigation then there's probably no reason to switch over.
      I'd be surprised if someone didn't draw lines between this module and Soma's awesome MarkupSimpleNavigation. Simply put I've been using MSN (...) for years, and it's been great – but there are some issues with it, particularly in the markup generation area, and it also does some things in a way that doesn't quite work for me – the xtemplates thing being one of these. In some ways less about features, and more about style, I guess 🙂
      Anyhow, in MarkupMenu I've tried to correct those little hiccups, modernise the default markup, and allow for more flexibility with placeholder variables and additional / different options. MarkupMenu was built for ProcessWire 3.0.112+ and with PHP 7.1+ in mind, it's installable with Composer, and I have a few additional ideas (such as conditional placeholders) still on my todo list.
      One more small(ish) difference is that MarkupMenu supports overriding default options via $config->MarkupMenu. I find myself redefining the default markup for every site, which until now meant that each site had a wrapper function for MarkupSimpleNavigation (to avoid code / config repetition), and this way I've been able to leave that out 🙂
      Requirements
      ProcessWire >= 3.0.112 PHP >= 7.1.0 If you're working on an earlier version of ProcessWire or PHP, use MarkupSimpleNavigation instead.
    • By teppo
      Hey folks!
      I'm happy to finally introduce a project I've been working on for quite a while now: it's called Wireframe, and it is an output framework for ProcessWire.
      Note that I'm posting this in the module development area, maily because this project is still in rather early stage. I've built a couple of sites with it myself, and parts of the codebase have been powering some pretty big and complex sites for many years now, but this should still be considered a soft launch 🙂
      --
      Long story short, Wireframe is a module that provides the "backbone" for building sites (and apps) with ProcessWire using an MVC (or perhaps MVVM – one of those three or four letter abbreviations anyway) inspired methodology. You could say that it's an output strategy, but I prefer the term "output framework" since in my mind the word "strategy" means something less tangible. A way of doing things, rather than a tool that actually does things.
      Wireframe (the module) provides a basic implementation for some familiar MVC concepts, such as Controllers and a View layer – the latter of which consists of layouts, partials, and template-specific views. There's no "model" layer, since in this context ProcessWire is the model. As a module Wireframe is actually quite simple – not even nearly the biggest one I've built – but there's still quite a bit of stuff to "get", so I've put together a demo & documentation site for it at https://wireframe-framework.com/.
      In addition to the core module, I'm also working on a couple of site profiles based on it. My current idea is actually to keep the module very light-weight, and implement most of the "opinionated" stuff in site profiles and/or companion modules. For an example MarkupMenu (which I released a while ago) was developed as one of those "companion modules" when I needed a menu module to use on the site profiles.
      Currently there are two public site profiles based on Wireframe:
      site-wireframe-docs is the demo&docs site mentioned above, just with placeholder content replaced with placeholder content. It's not a particularly complex site, but I believe it's still a pretty nice way to dig into the Wireframe module. site-wireframe-boilerplate is a boilerplate (or starter) site profile based on the docs site. This is still very much a work in progress, but essentially I'm trying to build a flexible yet full-featured starter profile you can just grab and start building upon. There will be a proper build process for resources, it will include most of the basic features one tends to need from site to site, etc. --
      Requirements and getting started:
      Wireframe can be installed just like any ProcessWire module. Just clone or download it to your site/modules/ directory and install. It doesn't, though, do a whole lot of stuff on itself – please check out the documentation site for a step-by-step guide on setting up the directory structure, adding the "bootstrap file", etc. You may find it easier to install one of the site profiles mentioned above, but note that this process involves the use of Composer. In the case of the site profiles you can install ProcessWire as usual and download or clone the site profile directory into your setup, but after that you should run "composer install" to get all the dependencies – including the Wireframe module – in place. Hard requirements for Wireframe are ProcessWire 3.0.112 and PHP 7.1+. The codebase is authored with current PHP versions in mind, and while running it on 7.0 may be possible, anything below that definitely won't work. A feature I added just today to the Wireframe module is that in case ProcessWire has write access to your site/templates/ directory, you can use the module settings screen to create the expected directories automatically. Currently that's all, and the module won't – for an example – create Controllers or layouts for you, so you should check out the site profiles for examples on these. (I'm probably going to include some additional helper features in the near future.)
      --
      This project is loosely based on an earlier project called pw-mvc, i.e. the main concepts (such as Controllers and the View layer) are very similar. That being said, Wireframe is a major upgrade in terms of both functionality and architecture: namespaces and autoloader support are now baked in, the codebase requires PHP 7, Controllers are classes extending \Wireframe\Controller (instead of regular "flat" PHP files), implementation based on a module instead of a collection of drop-in files, etc.
      While Wireframe is indeed still in a relatively early stage (0.3.0 was launched today, in case version numbers matter) for the most part I'm happy with the way it works, and likely won't change it too drastically anytime soon – so feel free to give it a try, and if you do, please let me know how it went. I will continue building upon this project, and I am also constantly working on various side projects, such as the site profiles and a few unannounced helper modules.
      I should probably add that while Wireframe is not hard to use, it is more geared towards those interested in "software development" type methodology. With future updates to the module, the site profiles, and the docs I hope to lower the learning curve, but certain level of "developer focus" will remain. Although of course the optimal outcome would be if I could use this project to lure more folks towards that end of the spectrum... 🙂
      --
      Please let me know what you think – and thanks in advance!
×
×
  • Create New...