{"id":13879953,"url":"https://github.com/contentful/contentful_middleman","last_synced_at":"2025-09-29T12:30:35.771Z","repository":{"id":15258725,"uuid":"17987821","full_name":"contentful/contentful_middleman","owner":"contentful","description":"Contentful Middleman is an extension to use the Middleman static site generator (Ruby) together with the API-driven Contentful CMS.","archived":true,"fork":false,"pushed_at":"2023-10-26T13:42:21.000Z","size":263,"stargazers_count":146,"open_issues_count":12,"forks_count":35,"subscribers_count":39,"default_branch":"master","last_synced_at":"2024-09-27T10:02:24.198Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://www.contentful.com","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"lastmansleeping/secure-reverse-proxy","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/contentful.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-03-21T17:19:27.000Z","updated_at":"2024-08-11T15:05:01.000Z","dependencies_parsed_at":"2022-08-25T11:10:31.490Z","dependency_job_id":null,"html_url":"https://github.com/contentful/contentful_middleman","commit_stats":null,"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/contentful%2Fcontentful_middleman","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/contentful%2Fcontentful_middleman/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/contentful%2Fcontentful_middleman/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/contentful%2Fcontentful_middleman/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/contentful","download_url":"https://codeload.github.com/contentful/contentful_middleman/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234619402,"owners_count":18861457,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-06T08:02:40.341Z","updated_at":"2025-09-29T12:30:30.467Z","avatar_url":"https://github.com/contentful.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"# Contentful Middleman\n\n[![Build Status](https://travis-ci.org/contentful/contentful_middleman.svg?branch=master)](https://travis-ci.org/contentful/contentful_middleman)\n\n[Contentful](https://www.contentful.com) provides a content infrastructure for digital teams to power content in websites, apps, and devices. Unlike a CMS, Contentful was built to integrate with the modern software stack. It offers a central hub for structured content, powerful management and delivery APIs, and a customizable web app that enable developers and content creators to ship digital products faster.\n\nContentful Middleman is a [Middleman](http://middlemanapp.com/) extension to use the Middleman static site generator together with [Contentful](https://www.contentful.com). It is powered by the [Contentful Ruby Gem](https://github.com/contentful/contentful.rb).\n\nExperience the power of Middleman while staying sane as a developer by letting end-users edit content in a web-based interface.\n\n\u003e The main release works for Middleman v4 starting on version `4.0.0`.\n\u003e\n\u003e If you are using Middleman v3, use older releases. Latest stable release is `3.0.0`\n\n\n## Installation\nAdd the following line to the Gemfile of your Middleman project:\n\n```\ngem \"contentful_middleman\"\n```\n\nThen as usual, run:\n\n```\nbundle install\n```\n\n## Usage\n\nRun `middleman contentful` in your terminal. This will fetch entries for the configured\nspaces and content types and put the resulting data in the\n[local data folder](https://middlemanapp.com/advanced/local-data/) as yaml files.\n\n### --rebuild option\n\nThe `contentful` command has a `--rebuild` option which will trigger a rebuild of your site only if there were changes between the last\nand the current import.\n\n## Configuration\n\nTo configure the extension, add the following configuration block to Middleman's config.rb:\n\n```ruby\nactivate :contentful do |f|\n  f.space         = SPACE\n  f.access_token  = ACCESS_TOKEN\n  f.cda_query     = QUERY\n  f.content_types = CONTENT_TYPES_MAPPINGS\nend\n```\n\nParameter                | Description\n----------               | ------------\nspace                    | Hash with an user choosen name for the space as key and the space id as value.\naccess_token             | Contentful Delivery API access token.\ncda_query                | Hash describing query configuration. See [contentful.rb](https://github.com/contentful/contentful.rb) for more info (look for filter options there). Note that by default only 100 entries will be fetched, this can be configured to up to 1000 entries using the `limit` option. Example: `f.cda_query = { limit: 1000 }`.\nclient_options           | Hash describing client configuration. See [contentful.rb](https://github.com/contentful/contentful.rb#client-configuration-options) for more info. This option should commonly be used to change Rate Limit Management, Include Resolution, Logging and Proxies.\ncontent_types            | Hash describing the mapping applied to entries of the imported content types.\ndefault_locale           | String with the value for the default locale for your space. Defaults to `'en-US'`.\nuse_preview_api          | Boolean to toggle the used API. Set it to `false` to use `cdn.contentful.com` (default value). Set it to `true` to use `preview.contentful.com`. More info in [the documentation](https://www.contentful.com/developers/documentation/content-delivery-api/#preview-api)\nall_entries              | Boolean to toggle multiple requests to the API for getting over 1000 entries. This uses a naive approach and can get rate limited. When using this, have in mind adding an `order` in your `:cda_query` . Default order is `order: 'sys.createdAt'`.\nall_entries_page_size    | Integer amount of items per page for `:all_entries` requests, allowing for smaller page sizes on content heavy requests.\nrebuild_on_webhook       | Boolean to toggle Webhook server. Server will run in port 5678, and will be expecting to receive Contentful Webhook calls on `/receive`.\nwebhook_timeout          | Integer (in seconds) for wait time after Webhook received for rebuilding. Only used if `:rebuild_on_webhook` is true. Defaults to 300 seconds.\nwebhook_controller       | Class for handling Webhook response, defaults to `::ContentfulMiddleman::WebhookHandler`.\nrich_text_mappings       | Hash with `'nodeType' =\u003e RendererClass` pairs determining overrides for the [`RichTextRenderer` library](https://github.com/contentful/rich-text-renderer.rb) configuration.\nbase_path                | String with path to your Middleman Application, defaults to current directory. Path is relative to your current location.\ndestination              | String with path within your base path under which to store the output yaml files. Defaults to `data`.\n\nYou can activate the extension multiple times to import entries from different spaces.\n\n## Entry mapping\n\nThe extension will transform every fetched entry before storing it as a yaml file in the local\ndata folder. If a custom mapper is not specified a default one will be used.\n\nThe default mapper will map fields, assets and linked entries.\n\n### Custom mappers\n\nYou can create your own mappers if you need so. The only requirements for a class to behave as a\nmapper are an initializer and a `map(context, entry)` instance method.\n\nThe initializer takes two parameters:\n\n  * A `Contentful::Array` of all entries for the current content model\n  * A `Middleman::Configuration::ConfigurationManager` object containing the Contentful configuration options set in `config.rb`\n\n[See BackrefMapper](https://github.com/contentful/contentful_middleman/blob/master/examples/mappers/backref.rb)\nfor an example use of entries.\n\n[See the Base mapper](https://github.com/contentful/contentful_middleman/blob/master/lib/contentful_middleman/mappers/base.rb)\nfor an example use of options.\n\nThe `map` method takes two parameters:\n\n  * A context object. All properties set on this object will be written to the yaml file\n  * An entry\n\nFollowing is an example of such custom mapper:\n\n```ruby\nclass MyAwesomeMapper\n  def initialize(entries, options)\n    @entries = entries\n    @options = options\n  end\n\n  def map(context, entry)\n    context.slug = entry.title.parameterize\n    #... more transformations\n  end\nend\n```\n\nIf you don't want to map all the fields by hand inherit from the Base mappper:\n\n```ruby\nclass MyAwesomeMapper \u003c ContentfulMiddleman::Mapper::Base\n  def map(context, entry)\n    super\n    # After calling super the context object\n    # will have a property for every field in the\n    # entry\n  end\nend\n```\n\nThere's also an example back-reference mapper in the examples directory for adding back-references onto entries that are linked to by other entries.\n\n#### Multiple Mappers\n\nIf you want to process a Content Type with multiple mappers, you can use the [Composite Design Pattern](https://en.wikipedia.org/wiki/Composite_pattern).\nThe Mapper code should look something similar to the following.\n\nThen you can attach as many Custom Mappers as you want to that one.\n\n```ruby\nclass CompositeMapper \u003c ContentfulMiddleman::Mapper::Base\n  @@mappers = []\n  def self.mappers\n    @@mappers\n  end\n\n  def map(context, entry)\n    super\n    mappers.each do |m|\n      m.map(context, entry)\n    end\n  end\nend\n```\n\nThen in your config.rb file:\n\n```ruby\nCompositeMapper.mappers \u003c\u003c YourMapper.new\nCompositeMapper.mappers \u003c\u003c OtherMapper.new\n\nactivate :contentful do |f|\n  '... your config here ...'\n  f.content_types = {content_type_name_you_want_to_map: {mapper: CompositeMapper, id: 'content_type_id'}}\nend\n```\n\n*NOTE*: This kind of Composite Mapper is static, therefore if you want to have multiple combinations of mappers\n for multiple entries, you'd need to write code a bit differently.\n\n### Rich Text *BETA*\n\nTo render rich text in your views, you can use the `rich_text` view helper.\n\nAn example using `erb`:\n\n```erb\n\u003c% data.my_space.my_type.each do |_, entry| %\u003e\n  \u003c%= rich_text(entry.rich_field) %\u003e\n\u003c% end %\u003e\n```\n\nThis will output the generated HTML generated by the [`RichTextRenderer` library](https://github.com/contentful/rich-text-renderer.rb).\n\n#### Adding custom renderers\n\nWhen using rich text, if you're planning to embed entries, then you need to create your custom renderer for them. You can read how create your own renderer classes [here](https://github.com/contentful/rich-text-renderer.rb#using-different-renderers).\n\nTo configure the mappings, you need to add them in your `activate` block like follows:\n\n```ruby\nactivate :contentful do |f|\n  # ... all the regular config ...\n  f.rich_text_mappings = { 'embedded-entry-block' =\u003e MyCustomRenderer }\nend\n```\n\nYou can also add renderers for all other types of nodes if you want to have more granular control over the rendering.\n\n#### Using the helper with multiple activated Contentful extensions\n\nIn case you have multiple activated extensions, and have different mapping configurations for them. You can specify which extension instance you want to pull the configuration from when using the helper.\n\nThe helper receives an additional optional parameter for the extension instance. By default it is `0`, indicating the first activated extension.\n\nThe instances are sequentially numbered in order of activation, starting from 0.\n\nSo, if for example you have 2 active instances with different configuration, to use the second instance configuration, you should call the helper as: `rich_text(entry.rich_field, 1)`.\n\n## Configuration: examples\n\n```ruby\nactivate :contentful do |f|\n  f.space         = {partners: 'space-id'}\n  f.access_token  = 'some_access_token'\n  f.cda_query     = { content_type: 'content-type-id', include: 1 }\n  f.content_types = { partner: 'content-type-id'}\nend\n```\n\nThe above configuration does the following:\n\n  * Sets the alias `partners` to the space with id _some-id_\n  * Sets the alias `partner` to the content type with id _content-type-id_\n  * Uses the default mapper to transform `partner` entries into yaml files (no mapper specified for the `partner` content type)\n\nEntries fetched using this configuration will be stored as yaml files in `data/partners/partner/ENTRY_ID.yaml`.\n\n```ruby\nclass Mapper\n  def map(context, entry)\n    context.title = \"#{entry.title}-title\"\n    #...\n  end\nend\n\nactivate :contentful do |f|\n  f.space         = {partners: 'space-id'}\n  f.access_token  = 'some_access_token'\n  f.cda_query     = { content_type: '1EVL9Bl48Euu28QEOa44ai', include: 1 }\n  f.content_types = { partner: {mapper: Mapper, id: 'content-type-id'}}\nend\n```\n\nThe above configuration is the same as the previous one only that this time we are setting a custom mapper\nfor the entries belonging to the `partner` content type.\n\n\n## Using imported entries in templates\n\nMiddleman will load all the yaml files stored in the local data folder. This lets you use all the imported\ndata into your templates.\n\nConsider that we have data stored under `data/partners/partner`. Then in our templates we could use that data like\nthis:\n\n```erb\n\u003ch1\u003ePartners\u003c/h1\u003e\n\u003col\u003e\n  \u003c% data.partners.partner.each do |id, partner| %\u003e\n    \u003cli\u003e\u003c%= partner[\"name\"] %\u003e\u003c/li\u003e\n  \u003c% end %\u003e\n\u003c/ol\u003e\n```\n\n### Rendering Markdown:\n\nIf you want to use markdown in your content types you manually have to render this to markdown.\nDepending on the markdown library you need to transform the data.\nFor Kramdown this would be:\n\n```\n\u003c%= Kramdown::Document.new(data).to_html %\u003e\n```\n\n### Locales\n\nIf you have localized entries, and want to display content for multiple locales.\nYou can now include `locale: '*'` in your CDA query.\n\nThen you have the following methods of accessing locales:\n\n* **Manual access**\n\nYou can access your localized fields by fetching the locale directly from the data\n\n```erb\n\u003ch1\u003ePartners\u003c/h1\u003e\n\u003col\u003e\n  \u003c% data.partners.partner.each do |id, partner| %\u003e\n    \u003cli\u003e\u003c%= partner[\"name\"]['en-US'] %\u003e\u003c/li\u003e\n  \u003c% end %\u003e\n\u003c/ol\u003e\n```\n\n* **Entry Helper**\n\nYou can also map an specific locale for all entry fields using `localize_entry`\n\n```erb\n\u003ch1\u003ePartners\u003c/h1\u003e\n\u003col\u003e\n  \u003c% data.partners.partner.each do |id, partner| %\u003e\n    \u003c% localized_partner = localize_entry(partner, 'es') %\u003e\n    \u003cli\u003e\u003c%= localized_partner[\"name\"] %\u003e\u003c/li\u003e\n  \u003c% end %\u003e\n\u003c/ol\u003e\n```\n\n* **Generic Field Helper**\n\nThe `localize` helper will map an specific locale to a field of your entry\n\n```erb\n\u003ch1\u003ePartners\u003c/h1\u003e\n\u003col\u003e\n  \u003c% data.partners.partner.each do |id, partner| %\u003e\n    \u003cli\u003eValue Field: \u003c%= localize(partner, 'name', 'en-US') %\u003e\u003c/li\u003e\n    \u003cli\u003eArray Field: \u003c%= localize(partner, 'phones', 'es') %\u003e\u003c/li\u003e\n  \u003c% end %\u003e\n\u003c/ol\u003e\n```\n\n* **Specific Field Type Helper**\n\nOr, you can use `localize_value` or `localize_array` if you want more granularity.\n\n\u003e This method is discouraged, as `localize` achieves the same goal and is a field-type\nagnostic wrapper of these methods.\n\n```erb\n\u003ch1\u003ePartners\u003c/h1\u003e\n\u003col\u003e\n  \u003c% data.partners.partner.each do |id, partner| %\u003e\n    \u003cli\u003eValue Field: \u003c%= localize_value(partner['name'], 'en-US') %\u003e\u003c/li\u003e\n    \u003cli\u003eArray Field: \u003c%= localize_array(partner['phones'], 'es') %\u003e\u003c/li\u003e\n  \u003c% end %\u003e\n\u003c/ol\u003e\n```\n\nIf your fields are not localized, the value of the field will be returned.\n\nIn case of the field being localized but no value being set for a given entry, it will use\na fallback locale, by default is `en-US` but can be specified as an additional\nparameter in all the mentioned calls.\n\n### Preview API Helper\n\nYou can use the `#with_preview` helper to try your Preview API content without having to\ngenerate the entire `data` structures.\n\nThis generates a new Preview Contentful Client and has a cache that will store your objects\nin memory until they are considered to need refresh.\n\nIt can be used like a Contentful Client:\n\n```erb\n\u003c% with_preview(space: 'cfexampleapi', access_token: 'b4c0n73n7fu1') do |preview| %\u003e\n  \u003c% entry = preview.entry('nyancat') %\u003e\n\n  \u003cp\u003eName: \u003c%= entry.name %\u003e\u003c/p\u003e\n\u003c% end %\u003e\n```\n\nIf you want to clear the cache to force a refresh:\n\n```erb\n\u003c% with_preview(space: 'cfexampleapi', access_token: 'b4c0n73n7fu1') do |preview| %\u003e\n  \u003c% preview.clear_cache %\u003e\n\u003c% end %\u003e\n```\n\n#### Caching Rules\n\n* Every preview client will be cached by Space/Access Token combination\n* Only `entry`, `entries`, `asset` and `assets` will be cached\n* Every call will be cached by it's query parameters and ID (if ID is applicable)\n* Each call will be considered, by default, stale after 3 tries or 2 hours\n* Cache can be cleared by calling `#clear_cache`, this applies per preview client\n\n#### Caching Configuration\n\nYou can configure `:tries` and `:expires_in` in the `#with_preview` call like this:\n\n```erb\n\u003c% with_preview(\n     space: 'cfexampleapi',\n     access_token: 'b4c0n73n7fu1',\n     tries: 20,                                                      # Set Tries to 20 before stale\n     expires_in: ContentfulMiddleman::Tools::PreviewProxy.minutes(5) # Set Expiration to 5 minutes\n   ) do |preview| %\u003e\n  \u003c!-- do your stuff --\u003e\n\u003c% end %\u003e\n```\n\n## Platform Specific Deployment Caveats\n\nFor platform specific issues, please look into the [DEPLOYING](./DEPLOYING.md) document. This document is expected to grow with user contributions.\nFeel free to add your own discoveries to that file by issuing a Pull Request.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcontentful%2Fcontentful_middleman","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcontentful%2Fcontentful_middleman","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcontentful%2Fcontentful_middleman/lists"}