{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\nFTL (Fluent Translation List) String IDs\nOur convention for string ID creation is the following:\n 1. String IDs should be all lower-case alphanumeric characters.\n 2. Words should be separated with hyphens.\n 3. IDs should be prefixed with the name of the template file (e.g. firefox-new-skyline for\n firefox-new-skyline.html)\n 4. If you need to create a new string for the same place on a page and to transition to it as it is translated, you can\n add a version suffix to the string ID: e.g. firefox-new-skyline-main-page-title-v2.\n 5. The ID should be as descriptive as possible to make sense to the developer, but could be anything as long as it\n adheres to the rules above.\nUsing brand names\nCommon Mozilla brand names are stored in a global brands.ftl file, in the form of terms. Terms are useful for keeping\nbrand names separated from the rest of the translations, so that they can be managed in a consistent way across all\ntranslated files, and also updated easily in a global context. In general the brand names in this file remain in English\nand should not be translated, however locales still have the choice and control to make adjustments should it suit their\nparticular language.\nOnly our own brands should be managed this way, brands from other companies should not. If you are concerned that\nthe brand is a common word and may be translated, leave a comment for the translators.\nNote: We are trying to phase out use of { -brand-name-firefox-browser } please use {\n-brand-name-firefox } browser.\n12 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n-brand-name = Firefox\nexample-about = About { -brand-name }.\nexample-update-successful = { -brand-name } has been updated.\n# \"Safari\" here refers to the competing web browser\nexample-compare = How does { -brand-name } compare to Safari?\nImportant: When adding a new term to brands.ftl, the new term should also be manually added to the mozilla-\nl10n/www-l10n repo for all locales. The reason for this is that if a term does not exist for a particular locale, then it\ndoes not fall back to English like a regular string does. Instead, the term variable name is displayed on the page.\nVariables\nSingle hash comments are applied only to the string immediately following them. They should be used to provide\nadditional context for the translators including:\n 1. What the values of variables are.\n 2. Context about where string appears on the page if it is not visible or references other elements on the page.\n 3. Explanations of English idioms and jargon that may be confusing to non-native speakers.\n# Variables:\n# $savings (string) - the percentage saved from the regular price, not including the %␣\n ˓→Examples: 50, 70\nexample-bundle-savings = Buy now for { $savings }% off.\n# Context: Used as an accessible text alternative for an image\nexample-bookmark-manager-alt = The bookmark manager window in { -brand-name-firefox }.\n# Context: This lists the various websites and magazines who have mentioned Firefox␣\n ˓→Relay.\n# Example: \"As seen in: FORBES magainze and LifeHacker\"\nexample-social-proof = As seen in:\nexample-privacy-on-every = Want privacy on every device?\n# \"You got it\" here is a casual answer to the previous question, \"Want privacy on every␣\n ˓→device?\"\nexample-you-got-it = You got it. Get { -brand-name-firefox } for mobile.\nHTML with attributes\nWhen passing HTML tags with attributes into strings for translation, remove as much room for error as possible by\nputting all the attributes and their values in a single variable. (This is most common with links and their href attributes\nbut we do occasionally pass classes with other tags.)\n# Variables:\n# $attrs (attrs) - link to https://www.mozilla.org/about/\nexample-created = { -brand-name-firefox } was created by { -brand-name-\n ˓→mozilla }.\n (continues on next page)\n1.2. Localization 13\nbedrock Documentation, Release 1.0\n (continued from previous page)\n# Variables:\n# $class (string) - CSS class used to replace brand name with wordmark logo\nexample-firefox-relay = Add { -brand-name-firefox-relay }\n{% set created_attrs = 'href=\"%s\" data-cta-type=\"link\" data-cta-text=\"created by Mozilla\"\n ˓→'|safe|format(url('mozorg.about.index')) %}\n

{{ ftl('example-created', attrs=created_attrs) }}

\n{{ ftl('example-firefox-relay', class_name='class=\"mzp-c-wordmark mzp-t-wordmark-md mzp-\n ˓→t-product-relay\"') }}\nObsolete strings\nWhen new strings are added to a page sometimes they update or replace old strings. Obsolete strings & IDs should\nbe removed from ftl files immediately if they are not being used as a fallback. If they are being kept as a fallback they\nshould be removed after 1-2 months.\nFallback\nIf you need to create a new string for the same place on a page and would like to keep the old one as a fallback, you can\nadd a version suffix to the new string ID: e.g. firefox-new-skyline-main-page-title-v2.\nexample-block-title-v2 = Security, reliability and speed — on every device, anywhere you␣\n ˓→go.\n# Obsolete string\nexample-block-title = Security, reliability and speed — from name you can trust.\nThe ftl helper function has the ability to accept a fallback string ID and is described in the next section.\nRemove\nIf the new string is fundamentally different a new string ID should be created and the old one deleted.\nFor example, if the page is going from talking about the Google Translate extension to promoting our own Firefox\nTranslate feature the old strings are not appropriate fall backs.\nThe old strings and IDs should be deleted:\nexample-translate-title = The To Google Translate extension makes translating the page␣\n ˓→you’re on easier than ever.\nexample-translate-content = Google Translate, with over 100 languages* at the ready, is␣\n ˓→used by millions of people around the world.\nThe new strings should have different IDs and not be versioned:\nexample-translate-integrated-title = { -brand-name-firefox } now comes with an␣\n ˓→integrated translation tool.\nexample-translate-integrated-content = Unlike some cloud-based alternatives, { -brand-\n ˓→name-firefox } translates text locally, so the content you’re translating doesn’t␣\n ˓→leave your machine.\n14 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nThe ftl_has_messages jinja helper would be useful here and is described in the next section.\nThe ftl helper function\nThe ftl() function takes a string ID and returns the string in the current language, or simplified english if the string\nisn’t translated. If you’d like to use a different string ID in the case that the primary one isn’t translated you can specify\nthat like this:\nftl('primary-string-id', fallback='fallback-string-id')\nWhen a fallback is specified it will be used only if the primary isn’t translated in the current locale. English locales\n(e.g. en-US, en-GB) will never use the fallback and will print the simplified english version of the primary string if not\noverridden in the more specific locale.\nYou can also pass in replacement variables into the ftl() function for use with fluent variables. If you had a variable\nin your fluent file like this:\nwelcome = Welcome, { $user }!\nYou could use that in a template like this:\n

{{ ftl('welcome', user='Dude') }}

\nFor our purposes these are mostly useful for things that can change, but which shouldn’t involve retranslation of a string\n(e.g. URLs or email addresses).\nYou may also request any other translation of the string (or the original English string of course) regardless of the\ncurrent locale.\n

{{ ftl('welcome', locale='en', user='Dude') }}

\nThis helper is available in Jinja templates and Python code in views. For use in a view you should always call it in the\nview itself:\n# views.py\nfrom lib.l10n_utils import render\nfrom lib.l10n_utils.fluent import ftl\ndef about_view(request):\n ftl_files = 'mozorg/about'\n hello_string = ftl('about-hello', ftl_files=ftl_files)\n render(request, 'about.html', {'hello': hello_string}, ftl_files=ftl_files)\nIf you need to use this string in a view, but define it outside of the view itself, you can use the ftl_lazy variant which\nwill delay evaluation until render time. This is mostly useful for defining messages shared among several views in\nconstants in a views.py or models.py file.\nWhether you use this function in a Python view or a Jinja template it will always use the default list of Fluent files\ndefined in the FLUENT_DEFAULT_FILES setting. If you don’t specify any additional Fluent files via the fluent_files\nkeyword argument, then only those default files will be used.\n1.2. Localization 15\nbedrock Documentation, Release 1.0\nThe ftl_has_messages helper function\nAnother useful template tool is the ftl_has_messages() function. You pass it any number of string IDs and it will\nreturn True only if all of those message IDs exist in the current translation. This is useful when you want to add a new\nblock of HTML to a page that is already translated, but don’t want it to appear untranslated on any page.\n{% if ftl_has_messages('new-title', 'new-description') %}\n

{{ ftl('new-title') }}

\n

{{ ftl('new-description') }}

\n{% else %}\n

{{ ftl('title') }}

\n

{{ ftl('description') }}

\n{% endif %}\nIf you’d like to have it return true when any of the given message IDs exist in the translation instead of requiring all of\nthem, you can pass the optional require_all=False parameter and it will do just that.\nThere is a version of this function for use in views called has_messages. It works exactly the same way but is meant\nto be used in the view Python code.\n# views.py\nfrom lib.l10n_utils import render\nfrom lib.l10n_utils.fluent import ftl, has_messages\ndef about_view(request):\n ftl_files = 'mozorg/about'\n if has_messages('about-hello-v2', 'about-title-v2',\n ftl_files=ftl_files):\n hello_string = ftl('about-hello-v2', ftl_files=ftl_files)\n title_string = ftl('about-title-v2', ftl_files=ftl_files)\n else:\n hello_string = ftl('about-hello', ftl_files=ftl_files)\n title_string = ftl('about-title', ftl_files=ftl_files)\n render(request, 'about.html', {'hello': hello_string, 'title': title_string}, ftl_\n ˓→files=ftl_files)\nSpecifying Fluent files\nYou have to tell the system which Fluent files to use for a particular template or view. This is done in either the page()\nhelper in a urls.py file, or in the call to l10n_utils.render() in a view.\nUsing the page() function\nIf you just need to render a template, which is quite common for bedrock, you will probably just add a line like the\nfollowing to your urls.py file:\nurlpatterns = [\n page('about', 'about.html'),\n page('about/contact', 'about/contact.html'),\n]\nTo tell this page to use the Fluent framework for l10n you just need to tell it which file(s) to use:\n16 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nurlpatterns = [\n page('about', 'about.html', ftl_files='mozorg/about'),\n page('about/contact', 'about/contact.html', ftl_files=['mozorg/about/contact',\n ˓→'mozorg/about']),\n]\nThe system uses the first (or only) file in the list to determine which locales are active for that URL. You can pass a\nstring or list of strings to the ftl_files argument. The files you specify can include the .ftl extension or not, and\nthey will be combined with the list of default files which contain strings for global elements like navigation and footer.\nThere will also be files for reusable widgets like the newsletter form, but those should always come last in the list.\nUsing the class-based view\nBedrock includes a generic class-based view (CBV) that sets up l10n for you. If you need to do anything fancier than\njust render the page, then you can use this:\nfrom lib.l10n_utils import L10nTemplateView\nclass AboutView(L10nTemplateView):\n template_name = 'about.html'\n ftl_files = 'mozorg/about'\nUsing that CBV will do the right things for l10n, and then you can override other useful methods (e.g.\nget_context_data) to do what you need. Also, if you do need to do anything fancy with the context, and you\nfind that you need to dynamically set the fluent files list, you can easily do so by setting ftl_files in the context\ninstead of the class attribute.\nfrom lib.l10n_utils import L10nTemplateView\nclass AboutView(L10nTemplateView):\n template_name = 'about.html'\n def get_context_data(self, **kwargs):\n ctx = super().get_context_data(**kwargs)\n ftl_files = ['mozorg/about']\n if request.GET.get('fancy'):\n ftl_files.append('fancy')\n ctx['ftl_files'] = ftl_files\n return ctx\nA common case is needing to use FTL files when one template is used, but not with another. In this case you would have\nsome logic to decide which template to use in the get_template_names() method. You can set the ftl_files_map\nclass variable to a dict containing a map of template names to the list of FTL files for that template (or a single file\nname if that’s all you need).\n# views.py\nfrom lib.l10n_utils import L10nTemplateView\n# class-based view example\nclass AboutView(L10nTemplateView):\n ftl_files_map = {\n (continues on next page)\n1.2. Localization 17\nbedrock Documentation, Release 1.0\n (continued from previous page)\n 'about_es.html': ['about_es']\n 'about_new.html': ['about']\n }\n def get_template_names(self):\n if self.request.locale.startswith('en'):\n template_name = 'about_new.html'\n elif self.request.locale.startswith('es'):\n template_name = 'about_es.html'\n else:\n # FTL system not used\n template_name = 'about.html'\n return [template_name]\nIf you need for your URL to use multiple Fluent files to determine the full list of active locales, for example when\nyou are redesigning a page and have multiple templates in use for a single URL depending on locale, you can use the\nactivation_files parameter. This should be a list of FTL filenames that should all be used when determining the full list\nof translations for the URL. Bedrock will gather the full list for each file and combine them into a single list so that the\nfooter language switcher works properly.\nAnother common case is that you want to keep using an old template for locales that haven’t yet translated the strings\nfor a new one. In that case you can provide an old_template_name to the class and include both that template and\ntemplate_name in the ftl_files_map. Once you do this the view will use the template in template_name only for\nrequests for an active locale for the FTL files you provided in the map.\nfrom lib.l10n_utils import L10nTemplateView\nclass AboutView(L10nTemplateView):\n template_name = 'about_new.html'\n old_template_name = \"about.html\"\n ftl_files_map = {\n \"about_new.html\": [\"about_new\", \"about_shared\"],\n \"about.html\": [\"about\", \"about_shared\"],\n }\nIn this example when the about_new FTL file is active for a locale, the about_new.html template will be rendered.\nOtherwise the about.html template would be used.\nUsing in a view function\nLastly there’s the good old function views. These should use l10n_utils.render directly to render the template with\nthe context. You can use the ftl_files argument with this function as well.\nfrom lib.l10n_utils import render\ndef about_view(request):\n render(request, 'about.html', {'name': 'Duder'}, ftl_files='mozorg/about')\n18 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nFluent File Configuration\nIn order for a Fluent file to be extracted through automation and sent out for localization, it must first be configured to\ngo through one or more distinct pipelines. This is controlled via a set of configuration files:\n • Vendor, locales translated by an agency, and paid for by Marketing (locales covered by staff are also included in\n this group).\n • Pontoon, locales translated by Mozilla contributors.\n • Special templates, for locales with dedicated templates that don’t go through the localization process (not cur-\n rently used).\nEach configuration file consists of a pre-defined set of locales for which each group is responsible for translating. The\nlocales defined in each file should not be changed without first consulting the with L10n team, and such changes should\nnot be a regular occurrence.\nTo establish a localization strategy for a Fluent file, it needs to be included as a path in one or more configuration files.\nFor example:\n[[paths]]\n reference = \"en/mozorg/mission.ftl\"\n l10n = \"{locale}/mozorg/mission.ftl\"\nYou can read more about configuration files in the L10n Project Configuration docs.\nImportant: Path definitions in Fluent configuration files are not source order dependent. A broad definition using a\nwild card can invalidate all previous path definitions for example. Paths should be defined carefully to avoid exposing\n.ftl files to unintended locales.\nUsing a combination of vendor and pontoon configuration offers a flexible but specific set of options to choose from\nwhen it comes to defining an l10n strategy for a page. The available choices are:\n 1. Staff locales.\n 2. Staff + select vendor locales.\n 3. Staff + all vendor locales.\n 4. Staff + vendor + pontoon.\n 5. All pontoon locales (for non-marketing content only).\nWhen choosing an option, it’s important to consider that vendor locales have a cost associated with them, and pontoon\nleans on the goodwill of our volunteer community. Typically, only non-marketing content should go through Pontoon\nfor all locales. Everything that is marketing related should feature one of the staff/vendor/pontoon configurations.\nFluent File Activation\nFluent files are activated automatically when processed from the l10n team’s repo into our own based on a couple of\nrules.\n 1. If a fluent file has a group of required strings, all of those strings must be present in the translation in order for it\n to be activated.\n 2. A translation must contain a minimum percent of the string IDs from the English file to be activated.\nIf both of these conditions are met the locale is activated for that particular Fluent file. Any view using that file as its\nprimary (first in the list) file will be available in that locale.\n1.2. Localization 19\nbedrock Documentation, Release 1.0\nDeactivation\nIf the automated system activates a locale but we for some reason need to ensure that this page remains unavailable in\nthat locale, we can add this locale to a list of deactivated locales in the metadata file for that FTL file. For example, say\nwe needed to make sure that the mozorg/mission.ftl file remained inactive for German, even though the translation is\nalready done. We would add de to the inactive_locales list in the metadata/mozorg/mission.json file:\n{\n \"active_locales\": [\n \"de\",\n \"fr\",\n \"en-GB\",\n \"en-US\",\n ],\n \"inactive_locales\": [\n \"de\"\n ],\n \"percent_required\": 85\n}\nThis would ensure that even though de appears in both lists, it will remain deactivated on the site. We could just remove\nit from the active list, but automation would keep attempting to add it back, so for now this is the best solution we have,\nand is an indication of the full list of locales that have satisfied the rules.\nAlternate Rules\nIt’s also possible to change the percentage of string completion required for activation on a per-file basis. In the same\nmetadata file as above, if a percent_required key exists in the JSON data (see above) it will be used as the minimum\npercent of string completion required for that file in order to activate new locales.\nNote: Once a locale is activated for a Fluent file it will NOT be automatically deactivated, even if the rules change.\nIf you need to deactivate a locale you should follow the Deactivation instructions.\nActivation Status\nYou can determine and use the activation status of a Fluent file in a view to make some decisions; what template to\nrender for example. The way you would do that is with the ftl_file_is_active function. For example:\n# views.py\nfrom lib.l10n_utils import L10nTemplateView\nfrom lib.l10n_utils.fluent import ftl_file_is_active\n# class-based view example\nclass AboutView(L10nTemplateView):\n ftl_files_map = {\n 'about.html': ['about']\n 'about_new.html': ['about_new', 'about']\n }\n def get_template_names(self):\n if ftl_file_is_active('mozorg/about_new'):\n (continues on next page)\n20 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n (continued from previous page)\n template_name = 'about_new.html'\n else:\n template_name = 'about.html'\n return [template_name]\n# function view example\ndef about_view(request):\n if ftl_file_is_active('mozorg/about_new'):\n template = 'mozorg/about_new.html'\n ftl_files = ['mozorg/about_new', 'mozorg/about']\n else:\n template = 'about.html'\n ftl_files = ['mozorg/about']\n render(request, template, ftl_files=ftl_files)\nActive Locales\nTo see which locales are active for a particular .ftl file you can either look in the metadata file for that .ftl file, which\nis the one with the same path but in the metadata folder instead of a locale folder in the www-l10n repository. Or if\nyou’d like something a bit nicer looking and more convenient there is the active_locales management command:\n$ ./manage.py l10n_update\n$ ./manage.py active_locales mozorg/mission\nThere are 91 active locales for mozorg/mission.ftl:\n- af\n- an\n- ar\n- ast\n- az\n- be\n- bg\n- bn\n...\nYou get an alphabetically sorted list of all of the active locales for that .ftl file. You should run ./manage.py\nl10n_update as shown above for the most accurate and up-to-date results.\n1.2. Localization 21\nbedrock Documentation, Release 1.0\nString extraction\nThe string extraction process for both new .ftl content and updates to existing .ftl content is handled through automation.\nOn each commit to main a command is run that looks for changes to the l10n/ and l10n-pocket/ directories. If a\nchange is detected, it will copy those files into a new branch in mozilla-l10n/www-l10n and then a bot will open a pull\nrequest containing those changes. Once the pull request has been reviewed and merged by the L10n team, everything\nis done.\nTo view the state of the latest automated attempt to open an L10N PR, see:\n • Mozorg L10N PR action\n • Pocket L10N PR action\n(We also just try to open L10N PRs every 3 hours, to catch any failed jobs that are triggered by a commit to main)\nCSS\nIf a localized page needs some locale-specific style tweaks, you can add the style rules to the page’s stylesheet like this:\nhtml[lang=\"it\"] #features li {\n font-size: 20px;\n}\nhtml[dir=\"rtl\"] #features {\n float: right;\n}\nIf a locale needs site-wide style tweaks, font settings in particular, you can add the rules to /media/css/l10n/\n{{LANG}}/intl.css. Pages on Bedrock automatically includes the CSS in the base templates with the l10n_css\nhelper function. The CSS may also be loaded directly from other Mozilla sites with such a URL: //mozorg.cdn.\nmozilla.net/media/css/l10n/{{LANG}}/intl.css.\nOpen Sans, the default font on mozilla.org, doesn’t offer non-Latin glyphs. intl.css can have @font-face rules to\ndefine locale-specific fonts using custom font families as below:\n • X-LocaleSpecific-Light: Used in combination with Open Sans Light. The font can come in 2 weights: normal\n and optionally bold\n • X-LocaleSpecific: Used in combination with Open Sans Regular. The font can come in 2 weights: normal and\n optionally bold\n • X-LocaleSpecific-Extrabold: Used in combination with Open Sans Extrabold. The font weight is 800 only\nHere’s an example of intl.css:\n@font-face {\n font-family: X-LocaleSpecific-Light;\n font-weight: normal;\n font-display: swap;\n src: local(mplus-2p-light), local(Meiryo);\n}\n@font-face {\n font-family: X-LocaleSpecific-Light;\n font-weight: bold;\n font-display: swap;\n (continues on next page)\n22 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n (continued from previous page)\n src: local(mplus-2p-medium), local(Meiryo-Bold);\n}\n@font-face {\n font-family: X-LocaleSpecific;\n font-weight: normal;\n font-display: swap;\n src: local(mplus-2p-regular), local(Meiryo);\n}\n@font-face {\n font-family: X-LocaleSpecific;\n font-weight: bold;\n font-display: swap;\n src: local(mplus-2p-bold), local(Meiryo-Bold);\n}\n@font-face {\n font-family: X-LocaleSpecific-Extrabold;\n font-weight: 800;\n font-display: swap;\n src: local(mplus-2p-black), local(Meiryo-Bold);\n}\nLocalizers can specify locale-specific fonts in one of the following ways:\n • Choose best-looking fonts widely used on major platforms, and specify those with the src: local(name)\n syntax\n • Find a best-looking free Web font, add the font files to /media/fonts/, and specify those with the src:\n url(path) syntax\n • Create a custom Web font to complement missing glyphs in Open Sans, add the font files to /media/fonts/\n l10n/, and specify those with the src: url(path) syntax. M+ 2c offers various international glyphs and\n looks similar to Open Sans, while Noto Sans is good for the bold and italic variants. You can create subsets of\n these alternative fonts in the WOFF and WOFF2 formats using a tool found on the Web. See Bug 1360812 for\n the Fulah (ff) locale’s example\nDevelopers should use the .open-sans mixin instead of font-family: 'Open Sans' to specify the default font\nfamily in CSS. This mixin has both Open Sans and X-LocaleSpecific so locale-specific fonts, if defined, will be applied\nto localized pages. The variant mixins, .open-sans-light and .open-sans-extrabold, are also available.\n1.2.2 All\nLocale-specific Templates\nWhile the ftl_has_messages template function is great in small doses, it doesn’t scale particularly well. A template\nfilled with conditional copy can be difficult to comprehend, particularly when the conditional copy has associated CSS\nand/or JavaScript.\nIn instances where a large amount of a template’s copy needs to be changed, or when a template has messaging targeting\none particular locale, creating a locale-specific template may be a good choice.\nLocale-specific templates function simply by naming convention. For example, to create a version of /firefox/new.\nhtml specifically for the de locale, you would create a new template named /firefox/new.de.html. This template\n1.2. Localization 23\nbedrock Documentation, Release 1.0\ncan either extend /firefox/new.html and override only certain blocks, or be entirely unique.\nWhen a request is made for a particular page, bedrock’s rendering function automatically checks for a locale-specific\ntemplate, and, if one exists, will render it instead of the originally specified (locale-agnostic) template.\nNote: Creating a locale-specific template for en-US was not possible when this feature was introduced, but it is now.\nSo you can create your en-US-only template and the rest of the locales will continue to use the default.\nSpecifying Active Locales in Views\nNormally we rely on activation tags in our translation files (.lang files) to determine in which languages a page will be\navailable. This will almost always be what we want for a page. But sometimes we need to explicitly state the locales\navailable for a page. The impressum page for example is only available in German and the template itself has German\nhard-coded into it since we don’t need it to be translated into any other languages. In cases like these we can send a list\nof locale codes with the template context and it will be the final list. This can be accomplished in a few ways depending\non how the view is coded.\nFor a plain view function, you can simply pass a list of locale codes to l10n_utils.render in the context using the name\nactive_locales. This will be the full list of available translations. Use add_active_locales if you want to add languages\nto the existing list:\ndef french_and_german_only(request):\n return l10n_utils.render(request, 'home.html', {'active_locales': ['de', 'fr'])\nIf you don’t need a custom view and are just using the page() helper function in your urls.py file, then you can similarly\npass in a list:\npage('about', 'about.html', active_locales=['en-US', 'es-ES']),\nOr if your view is even more fancy and you’re using a Class-Based-View that inherits from LangFilesMixin (which it\nmust if you want it to be translated) then you can specify the list as part of the view Class definition:\nclass MyView(LangFilesMixin, View):\n active_locales = ['zh-CN', 'hi-IN']\nOr in the urls.py when using a CBV:\nurl(r'about/$', MyView.as_view(active_locales=['de', 'fr'])),\nThe main thing to keep in mind is that if you specify active_locales that will be the full list of localizations available\nfor that page. If you’d like to add to the existing list of locales generated from the lang files then you can use the\nadd_active_locales name in all of the same ways as active_locales above. It’s a list of locale codes that will be added\nto the list already available. This is useful in situations where we would have needed the l10n team to create an empty\n.lang file with an active tag in it because we have a locale-specific-template with text in the language hard-coded into\nthe template and therefore do not otherwise need a .lang file.\n24 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.2.3 Adding new L10N integrations\nBedrock, as a platform, can operate in different modes, and it is possible (necessary, even) to support multiple L10N\npipelines, so that each mode of operation can have its own distinct Fluent files and translation strategy.\nAs of Summer 2022, there are two separate L10N integrations within Bedrock:\n • Mozilla.org (“Mozorg mode”)\n • Pocket Marketing Pages (“Pocket mode”)\nThese integrations are similar in their approach, but not identical in how they run. They use different translations\nstrategies, which requires slightly different data flows.\nMoving L10N data (essentially Fluent .ftl files) happens via various automation steps, which aren’t captured here, as\nthey are more about infrastructure and operations. However, what follows outlines the steps needed to add a new L10N\nintegration (for “newintegration”) to Bedrock.\n 1. FILE SETUP (Bedrock developer)\nAdd a directory for the source (en) Fluent strings that will need translation.\nNote: For source Fluent files currently. . .\n • . . . Mozorg uses ./l10n/\n • . . . Pocket uses ./l10n-pocket/\nAdd the following files:\n./l10n-newintegration/\n./l10n-newintegration/en/ # This is where source Fluent templates go for 'newintegration'\n./l10n-newintegration/en/configs/pontoon.toml # If using community/Pontoon translations␣\n ˓→at all\n./l10n-newintegration/en/configs/vendor.toml # If using a paid-for translation service␣\n ˓→such as Smartling\n./l10n-newintegration/en/configs/special-templates.toml # Only needed to exclude␣\n ˓→certain files from all community AND vendor translation. e.g. we use staff translation␣\n ˓→only.\n./l10n-newintegration/l10n-pontoon.toml # If using community/Pontoon translations at all\n./l10n-newintegration/l10n-vendor.toml # If using a paid-for translation service such␣\n ˓→as Smartling\n./data/l10n-newintegration-team/ # leave this empty - it will be populated via a git␣\n ˓→sync using data FROM the l10n team\nFor the exact content of each .toml or .json file, see the examples in ./l10n/ and ./l10n-pocket/ for inspiration -\nthey’re not too hard to work out. The .toml files outside of /en/ basically point to the ones in /en/configs/ and are\na ‘gateway’ through which we spec which config files are relevant to which translation stragegy (community or vendor\n- or neither if it’s staff-only translation).\n 2. REPO SETUP (Bedrock and/or L10N team admin)\nYou will need to set up one or two new repos, to hold the translation files as part of the pipeline.\ni. A repo in where the files are sent to in https://github.com/mozilla-l10n/ for the L10N team’s automation\nto pick up.\n1.2. Localization 25\nbedrock Documentation, Release 1.0\nFor example, Mozorg uses github.com/mozilla-l10n/www-l10n/ and Pocket uses github.com/mozilla-l10n/\nwww-pocket-l10n/. Your new github.com/mozilla-l10n/www-newintegration-l10n/ repo will be needed\nregardless of who does the actual translation work.\n ii. An optional repo where files are post-processed following translation.\nIf relevant, this will live in github.com/mozmeao/ - for example github.com/mozmeao/\nwww-newintegration-l10n/\nImportant: If you are not using Pontoon/community translations, you do NOT need to create this repo. Why?\nIf the translations are done by the community (via Pontoon), there is a possibility that not enough of the strings will\nbe translated in order to render the content in the relevant locale. We run a CI task to determine whether a locale has\nenough translated strings to be considered ‘active’. At the moment, only Mozorg uses this pattern. The Pocket-mode\ntranslations do not have their activation measured because their translations come entirely from a vendor and we expect\nthe Pocket strings to be 100% translated.\n 3. CI SETUP (Bedrock dev)\nOnly relevant if using Pontoon community translations. Details of how MozMarRobot is hooked are best gleaned from\nlooking at https://gitlab.com/mozmeao/www-fluent-update.\nIn short, once new translations land in the string-source repo (e.g. github.com/mozilla-l10n/\nwww-newintegration-l10n) they are cloned over to the activation-check repo github.com/mozmeao/\nwww-newintegration-l10n/ by CI and later pulled into Bedrock from there.\n 4. CONFIGURE SETTINGS (Bedrock dev).\nYou’ll also have to update settings so that when the site is in ‘newintegration’ mode, it knows which L10N-related local\nfolders and remote repos to use. Look in settings/__init__.py to see what we did for Pocket mode.\nYou’ll also have to set up new env vars to provide the new repo and filepath settings’ values, which will mean updating\ngithub.com/mozmeao/www-config/ and possibly getting new secrets provisioned in Kubernetes if you need to use\na separate auth token for github.com/mozilla-l10n/. (You may not.)\nNote that if you are not using community/Pontoon translations - and therefore you don’t need to use an intermediary\nrepo to calculate activation status - you can just use the mozilla-l10n/www-newintegration-l10n repo for both\noutbound and inbound translations - look at the Pocket Mode setting for an example of this.\n 5. EXPAND L10N UPDATE SCRIPT (Bedrock dev).\nUploading strings for translation\nUploading `en-locale source strings from Bedrock to the github.com/mozilla-l10n/ repos is handled by\nbedrock/bin/open-ftl-pr.sh. This file requires no specific code changes to support a new integration as long\nas you have already set up a SITE_MODE for ‘newintegration’.\nHowever, you do need to add a new entry to bedrock/.gitlab-ci.yml – copy the update-l10n step, in a similar\nway to how it’s been duplicated for update-pocket-l10n.\nDownloading translated strings\nUpdate the configuration dict at the top of bedrock/lib/l10n_utils/management/commands/l10n_update.py\nso that when that management command is run, it will pull down the appropriate translations for “newintegration”.\nTip: to test drive things, you can fork the real repos and test against your forks by specifying them via local env vars.\n 6. VENDOR SETUP (L10N Team)\nThe vendor (e.g. Smartling) will need to add the new string-source repo (github.com/mozilla-l10n/\nwww-newintegration-l10n) to its configuration. Once this is done new translations from the vendor will be added\n26 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nto that repo, and synced down to Bedrock. This step is out of our hands, but the vendor’s technical contact should be\nable to make it happen.\n 7. PONTOON SETUP (L10N Team)\nDetails to come for setting up community translations using Pontoon. (Contributions about this aspect are welcome!)\n1.3 Developing on Bedrock\n1.3.1 Managing Dependencies\nFor Python we use pip-compile from pip-tools to manage dependencies expressed in our requirements files.\npip-compile is wrapped up in Makefile commands, to ensure we use it consistently.\nIf you add a new Python dependency (eg to requirements/prod.in or requirements/dev.in) you can generate\na pinned and hash-marked addition to our requirements files just by running:\nmake compile-requirements\nand committing any changes that are made. Please re-build your docker image and test it with make build test to\nbe sure the dependency does not cause a regression.\nSimilarly, if you upgrade a pinned dependency in an *.in file, run make compile-requirements then rebuild, test\nand commit the results\nTo check for stale Python dependencies (basically pip list -o but in the Docker container):\nmake check-requirements\nFor Node packages we use NPM, which should already be installed alongside Node.js.\nFront-end Dependencies\nOur team maintains a few dependencies that we serve on Bedrock’s front-end.\n • @mozilla-protocol/core: Bedrock’s primary design system\n • @mozmeao/cookie-helper: A complete cookies reader/writer framework\n • @mozmeao/dnt-helper: Do Not Track (DNT) helper\n • @mozmeao/trafficcop: Used for A/B testing page variants\nBecause they are all published on NPM, install the packages and keep up-to-date with the latest version of each de-\npendency by running an npm install. For further documentation on installing NPM packages, check out the official\ndocumentation.\n1.3. Developing on Bedrock 27\nbedrock Documentation, Release 1.0\n1.3.2 Asset Management and Bundling\nBedrock uses Webpack to manage front-end asset processing and bundling. This includes processing and minifying\nJavaScript and SCSS/CSS bundles, as well as managing static assets such as images, fonts, and other common file\ntypes.\nWhen developing on bedrock you can start Webpack by running make run when using Docker, or npm start when\nrunning bedrock locally.\nOnce Webpack has finished compiling, a local development server will be available at localhost:8000. When Webpack\ndetects changes to a JS/SCSS file, it will automatically recompile the bundle and then refresh any page running locally\nin the browser.\nWebpack Configuration\nWe have two main Webpack config files in the root directory:\nThe webpack.static.config.js file is responsible for copying static assets, such as images and fonts, from the\n/media/ directory over to the /assets/ directory. This is required so Django can serve them correctly.\nThe webpack.config.js file is responsible for processing JS and SCSS files in the /media/ directory and compiling\nthem into the /assets/ directory. This config file also starts a local development server and watches for file changes.\nWe use two separate config files to keep responsibilities clearly defined, and to make the configs both shorter and easier\nto follow.\nNote: Because of the large number of files used in bedrock, only JS and SCSS files managed by webpack.config.js\nare watched for changes when in development mode. This helps save on memory consumption. The implication of this\nis that files handled by webpack.static.config.js are only copied over when Webpack first runs. If you update an\nimage for example, then you will need to stop and restart Webpack to pick up the change. This is not true for JS and\nSCSS files, which will be watched for change automatically.\nAsset Bundling\nAsset bundles for both JS and SCSS are defined in ./media/static-bundles.json. This is the file where you can\ndefine the bundle names that will get used in page templates. For example, a CSS bundle can be defined as:\n\"css\": [\n {\n \"files\": [\n \"css/firefox/new/basic/download.scss\"\n ],\n \"name\": \"firefox_new_download\"\n }\n]\nWhich can then be referenced in a page template using:\n{{ css_bundle('firefox_new_download') }}\nA JS bundle can be defied as:\n28 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n\"js\": [\n {\n \"files\": [\n \"protocol/js/protocol-modal.js\",\n \"js/firefox/new/basic/download.js\"\n ],\n \"name\": \"firefox_new_download\"\n }\n]\nWhich can then be referenced in a page template using:\n{{ js_bundle('firefox_new_download') }}\nOnce you define a bundle in static-bundles.json, the webpack.config.js file will use these as entrypoints for\ncompiling JS and CSS and watching for changes.\n1.3.3 Writing JavaScript\nBedrock’s Webpack configuration supports some different options for writing JavaScript:\nDefault Configuration\nWrite example-script.js using ES5 syntax and features. Webpack will bundle the JS as-is, without any additional\npre-processing.\nBabel Configuration\nWrite example-script.es6.js using ES2015+ syntax. Webpack will transpile the code to ES5 using Babel. This\nis useful when you want to write modern syntax but still support older browsers.\nImportant: Whilst Babel will transpile most modern JS syntax to ES5 when suitable fallbacks exist, it won’t auto-\nmatically include custom polyfills for everything since these can start to greatly increase bundle size. If you want to\nuse Promise or async/await functions for example, then you will need to load polyfills for those. This can be done\neither at the page level, or globally in lib.js if it’s something that multiple pages would benefit from. But please pick\nand choose wisely, and be concious of performance.\nFor pages that are served to Firefox browsers only, such as /whatsnew, it is also possible to write native ES2015+\nsyntax and serve that directly in production. Here there is no need to include the .es6.js file extension. Instead, you\ncan simply use .js instead. The rules that which files you can do this in are defined in our ESLint config.\n1.3. Developing on Bedrock 29\nbedrock Documentation, Release 1.0\n1.3.4 Writing URL Patterns\nURL patterns should be the entire URL you desire, minus any prefixes from URLs files importing this one, and including\na trailing slash. You should also give the URL a name so that other pages can reference it instead of hardcoding the\nURL. Example:\npath(\"channel/\", channel, name=\"mozorg.channel\")\nIf you only want to render a template and don’t need to do anything else in a custom view, Bedrock comes with a handy\nshortcut to automate all of this:\nfrom bedrock.mozorg.util import page\npage(\"channel/\", \"mozorg/channel.html\")\nYou don’t need to create a view. It will serve up the specified template at the given URL (the first parameter. see the\nDjango docs for details). You can also pass template data as keyword arguments:\npage(\"channel/\", \"mozorg/channel.html\",\n latest_version=product_details.firefox_versions[\"LATEST_FIREFOX_VERSION\"])\nThe variable latest_version will be available in the template.\n1.3.5 Finding Templates by URL\nGeneral Structure\nBedrock follows the Django app structure and most templates are easy to find by matching URL path segments to\nfolders and files within the correct app.\nURL: https://www.mozilla.org/en-US/firefox/features/private-browsing/\nTemplate path: bedrock/bedrock/firefox/templates/firefox/features/private-browsing.html\nTo get from URL to template path:\n • Ignore https://www.mozilla.org and the locale path segment /en-US. The next path segment is the app\n name /firefox.\n • From the root folder of bedrock, find the app’s template folder at bedrock/{app}/templates/{app}\n • Match remaining URL path segments (/features/private-browsing) to the template folder’s structure (/\n features/private-browsing.html)\nNote: mozorg is the app name for the home page and child pages related to Mozilla Corporation (i.e. About, Contact,\nDiversity).\n30 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nWhatsnew and Firstrun\nThese pages are specific to Firefox browsers, and only appear when a user updates or installs and runs a Firefox browser\nfor the first time. The URL and template depend on what Firefox browser and version are in use.\nNote: There may be extra logic in the app’s views.py file to change the template based on locale or geographic\nlocation as well.\nFirefox release\nVersion number is digits only.\nWhatsnew URL: https://www.mozilla.org/en-US/firefox/99.0/whatsnew/\nTemplate path: https://github.com/mozilla/bedrock/tree/main/bedrock/firefox/templates/firefox/whatsnew\nFirstrun URL: https://www.mozilla.org/en-US/firefox/99.0/firstrun/\nTemplate path: https://github.com/mozilla/bedrock/blob/main/bedrock/firefox/templates/firefox/firstrun/firstrun.html\nFirefox Nightly\nVersion number is digits and a1.\nWhatsnew URL: https://www.mozilla.org/en-US/firefox/99.0a1/whatsnew/\nTemplate path:\nhttps://github.com/mozilla/bedrock/blob/main/bedrock/firefox/templates/firefox/nightly/whatsnew.html\nFirstrun URL: https://www.mozilla.org/en-US/firefox/nightly/firstrun/\nTemplate path: https://github.com/mozilla/bedrock/tree/main/bedrock/firefox/templates/firefox/nightly\nFirefox Developer\nVersion number is digits and a2.\nWhatsnew URL: https://www.mozilla.org/en-US/firefox/99.0a2/whatsnew/\nTemplate path:\nhttps://github.com/mozilla/bedrock/blob/main/bedrock/firefox/templates/firefox/developer/whatsnew.html\nFirstrun URL: https://www.mozilla.org/en-US/firefox/99.0a2/firstrun/\nTemplate path:\nhttps://github.com/mozilla/bedrock/blob/main/bedrock/firefox/templates/firefox/developer/firstrun.html\n1.3. Developing on Bedrock 31\nbedrock Documentation, Release 1.0\nRelease Notes\nRelease note templates live here: https://github.com/mozilla/bedrock/tree/main/bedrock/firefox/templates/firefox/\nreleases\nNote: Release note content is pulled in from an external data source.\n • Firefox release: https://www.mozilla.org/en-US/firefox/99.0.1/releasenotes/\n • Firefox Developer and Beta: https://www.mozilla.org/en-US/firefox/100.0beta/releasenotes/\n • Firefox Nightly: https://www.mozilla.org/en-US/firefox/101.0a1/releasenotes/\n • Firefox Android: https://www.mozilla.org/en-US/firefox/android/99.0/releasenotes/\n • Firefox iOS: https://www.mozilla.org/en-US/firefox/ios/99.0/releasenotes/\n1.3.6 Optimizing Images\nImages can take a long time to load and eat up a lot of bandwidth. Always take care to optimize images before uploading\nthem to the site.\nThe script img.sh can be used to optimize images locally on the command line:\n 1. Before you run it for the first time you will need to run npm install to install dependencies\n 2. Add the image files to git’s staging area git add *\n 3. Run the script ./bin/img.sh\n 4. The optimized files will not automatically be staged, so be sure to add them before commiting\nThe script will:\n • optimize JPG and PNG files using tinypng (\n – this step is optional since running compression on the same images over and over degrades them)\n – you will be prompted to add a TinyPNG API key\n • optimize SVG images locally with svgo\n • check that SVGs have a viewbox (needed for IE support)\n • check that images that end in -high-res have low res versions as well\n1.3.7 Embedding Images\nImages should be included on pages using one of the following helper functions.\n32 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nPrimary image helpers\nThe following image helpers support the most common features and use cases you may encounter when coding pages:\nstatic()\nFor a simple image, the static() function is used to generate the image URL. For example:\n\"Firefox\"\nwill output an image:\n\"Firefox\"\nresp_img()\nFor responsive images, where we want to specify multiple different image sizes and let the browser select which is best\nto use.\nThe example below shows how to serve an appropriately sized, responsive red panda image:\nresp_img(\n url=\"img/panda-500.png\",\n srcset={\n \"img/panda-500.png\": \"500w\",\n \"img/panda-750.png\": \"750w\",\n \"img/panda-1000.png\": \"1000w\"\n },\n sizes={\n \"(min-width: 1000px)\": \"calc(50vw - 200px)\",\n \"default\": \"calc(100vw - 50px)\"\n }\n)\nThis would output:\n\"\"'\nIn the above example we specified the available image sources using the srcset parameter. We then used sizes to\nsay:\n • When the viewport is greater than 1000px wide, the panda image will take up roughly half of the page width.\n • When the viewport is less than 1000px wide, the panda image will take up roughly full page width.\nThe default image src is what we specified using the url param. This is also what older browsers will fall back to\nusing. Modern browsers will instead pick the best source option from srcset (based on both the estimated image size\nand screen resolution) to satisfy the condition met in sizes.\n1.3. Developing on Bedrock 33\nbedrock Documentation, Release 1.0\nNote: The value default in the second sizes entry above should be used when you want to omit a media query.\nThis makes it possible to provide a fallback size when no other media queries match.\nAnother example might be to serve a high resolution alternative for a fixed size image:\nresp_img(\n url=\"img/panda.png\",\n srcset={\n \"img/panda-high-res.png\": \"2x\"\n }\n)\nThis would output:\n\"\"\nHere we don’t need a sizes attribute, since the panda image is fixed in size and small enough that it won’t need to\nresize along with the browser window. Instead the srcset image includes an alternate high resolution source URL,\nalong with a pixel density descriptor. This can then be used to say:\n • When a browser specifies a device pixel ratio of 2x or greater, use panda-high-res.png.\n • When a browser specifies a device pixel ration of less than 2x, use panda.png.\nThe resp_img() helper also supports localized images by setting the 'l10n' parameter to True`:\nresp_img(\n url=\"img/panda-500.png\",\n srcset={\n \"img/panda-500.png\": \"500w\",\n \"img/panda-750.png\": \"750w\",\n \"img/panda-1000.png\": \"1000w\"\n },\n sizes={\n \"(min-width: 1000px)\": \"calc(50vw - 200px)\",\n \"default\": \"calc(100vw - 50px)\"\n },\n optional_attributes={\n \"l10n\": True\n }\n)\nThis would output (assuming de was your locale):\n\"\"'\nFinally, you can also specify any other additional attributes you might need using optional_attributes:\nresp_img(\n url=\"img/panda-500.png\",\n srcset={\n (continues on next page)\n34 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n (continued from previous page)\n \"img/panda-500.png\": \"500w\",\n \"img/panda-750.png\": \"750w\",\n \"img/panda-1000.png\": \"1000w\"\n },\n sizes={\n \"(min-width: 1000px)\": \"calc(50vw - 200px)\",\n \"default\": \"calc(100vw - 50px)\"\n },\n optional_attributes={\n \"alt\": \"Red Panda\",\n \"class\": \"panda-hero\",\n \"height\": \"500\",\n \"l10n\": True,\n \"loading\": \"lazy\",\n \"width\": \"500\"\n }\n)\npicture()\nFor responsive images, where we want to serve different images, or image types, to suit different display sizes.\nThe example below shows how to serve a different image for desktop and mobile sizes screens:\npicture(\n url=\"img/panda-mobile.png\",\n sources=[\n {\n \"media\": \"(max-width: 799px)\",\n \"srcset\": {\n \"img/panda-mobile.png\": \"default\"\n }\n },\n {\n \"media\": \"(min-width: 800px)\",\n \"srcset\": {\n \"img/panda-desktop.png\": \"default\"\n }\n }\n ]\n)\nThis would output:\n\n \n \n \"\"\n\nIn the above example, the default image src is what we specifed using the url param. This is also what older browsers\nwill fall back to using. We then used the sources parameter to specify one or more alternate image elements,\n1.3. Developing on Bedrock 35\nbedrock Documentation, Release 1.0\nwhich modern browsers can take advantage of. For each , media lets us specify a media query as a condition\nfor when to load an image, and srcset lets us specify one or more sizes for each image.\nNote: The value default in the srcset entry above should be used when you want to omit a descriptor. In this\nexample we only have one entry in srcset (meaning it will be chosen immediately should the media query be satisfied),\nhence we omit a descriptor value.\nA more complex example might be when we want to load responsively sized, animated gifs, but also offer still images\nfor users who set (prefers-reduced-motion: reduce):\npicture(\n url=\"img/dancing-panda-500.gif\",\n sources=[\n {\n \"media\": \"(prefers-reduced-motion: reduce)\",\n \"srcset\": {\n \"img/sleeping-panda-500.png\": \"500w\",\n \"img/sleepinng-panda-750.png\": \"750w\",\n \"img/sleeping-panda-1000.png\": \"1000w\"\n },\n \"sizes\": {\n \"(min-width: 1000px)\": \"calc(50vw - 200px)\",\n \"default\": \"calc(100vw - 50px)\"\n }\n },\n {\n \"media\": \"(prefers-reduced-motion: no-preference)\",\n \"srcset\": {\n \"img/dancing-panda-500.gif\": \"500w\",\n \"img/dancing-panda-750.gif\": \"750w\",\n \"img/dancing-panda-1000.gif\": \"1000w\"\n },\n \"sizes\": {\n \"(min-width: 1000px)\": \"calc(50vw - 200px)\",\n \"default\": \"calc(100vw - 50px)\"\n }\n }\n ]\n)\nThis would output:\n\n \n \n \"\"\n\n36 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nIn the above example we would default to loading animated gifs, but if a user agent specified\n(prefers-reduced-motion: reduce) then the browser would load static png files instead. Multiple image\nsizes are also supported for each using srcset and sizes.\nAnother type of use case might be to serve different image formats, so capable browsers can take advantage of more\nefficient encoding:\npicture(\n url=\"img/red-panda.png\",\n sources=[\n {\n \"type\": \"image/webp\",\n \"srcset\": {\n \"img/red-panda.webp\": \"default\"\n }\n }\n ]\n)\nThis would output:\n\n \n \"\"\n\nIn the above example we use sources to specify an alternate image with a type attribute of image/webp. This lets\nbrowsers that support WebP to download red-panda.webp, whilst older browsers would download red-panda.png.\nLike resp_img(), the picture() helper also supports L10n images and other useful attributes via the\noptional_attributes parameter:\npicture(\n url=\"img/panda-mobile.png\",\n sources=[\n {\n \"media\": \"(max-width: 799px)\",\n \"srcset\": {\n \"img/panda-mobile.png\": \"default\"\n }\n },\n {\n \"media\": \"(min-width: 800px)\",\n \"srcset\": {\n \"img/panda-desktop.png\": \"default\"\n }\n }\n ],\n optional_attributes={\n \"alt\": \"Red Panda\",\n \"class\": \"panda-hero\",\n \"l10n\": True,\n \"loading\": \"lazy\",\n }\n)\n1.3. Developing on Bedrock 37\nbedrock Documentation, Release 1.0\nWhich image helper should you use?\nThis is a good question. The answer depends entirely on the image in question. A good rule of thumb is as follows:\n • Is the image a vector format (e.g. .svg)?\n – If yes, then for most cases you can simply use static().\n • Is the image a raster format (e.g. .png or .jpg)?\n – Is the same image displayed on both large and small viewports? Does the image need to scale as the\n browser resizes? If yes to both, then use resp_img() with both srcset and sizes.\n – Is the image fixed in size (non-responsive)? Do you need to serve a high resolution version? If yes to\n both, then use resp_img() with just srcset.\n • Does the source image need to change depending on a media query (e.g serve a different image on both desktop\n and mobile)? If yes, then use picture() with media and srcset.\n • Is the image format only supported in certain browsers? Do you need to provide a fallback? If yes to both, then\n use picture() with type and srcset.\nSecondary image helpers\nThe following image helpers are less commonly used, but exist to support more specific use cases. Some are also\nencapsulated as features inside inside of primary helpers, such as l1n_img().\nl10n_img()\nImages that have translatable text can be handled with l10n_img():\n\nThe images referenced by l10n_img() must exist in media/img/l10n/, so for above example, the im-\nages could include media/img/l10n/en-US/firefox/os/have-it-all/messages.jpg and media/img/l10n/\nes-ES/firefox/os/have-it-all/messages.jpg.\nqrcode()\nThis is a helper function that will output SVG data for a QR Code at the spot in the template where it is called. It caches\nthe results to the data/qrcode_cache directory, so it only generates the SVG data one time per data and box_size\ncombination.\nqrcode(\"https://accounts.firefox.com\", 30)\nThe first argument is the data you’d like to encode in the QR Code (usually a URL), and the second is the “box size”.\nIt’s a parameter that tells the generator how large to set the height and width parameters on the XML SVG tag, the units\nof which are “mm”. This can be overriden with CSS so you may not need to use it at all. The box_size parameter is\noptional.\n38 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.3.8 Using Large Assets\nWe don’t want to (and if large enough GitHub won’t let us) commit large files to the bedrock repo. Files such as large\nPDFs or very-high-res JPG files (e.g. leadership team photos), or videos are not well-tracked in git and will make every\ncheckout after they’re added slower and this diffs less useful. So we have another domain at which we upload these\nfiles: assets.mozilla.net\nThis domain is simply an AWS S3 bucket with a CloudFront CDN (Content Delivery Network) in front of it. It is\nhighly available and fast. We’ve made adding files to this domain very simple using git-lfs. You simply install git-lfs,\nclone our assets.mozilla.net repo, and then add and commit files under the assets directory there as usual. Open a\npull request, and once it’s merged it will be automatically uploaded to the S3 bucket and be available on the domain.\nFor example, if you add a file to the repo under assets/pdf/the-dude-abides.pdf, it will be available as https:\n//assets.mozilla.net/pdf/the-dude-abides.pdf. Once that is done you can link to that URL from bedrock as you would\nany other URL.\n1.3.9 Writing Migrations\nBedrock uses Django’s built-in Migrations framework for its database migrations, and has no custom database routing,\netc. So, no big surprises here – write things as you regularly would.\nHowever, as with any complex system, care needs to be taken with schema changes that drop or rename database\ncolumns. Due to the way the rollout process works (ask for details directly from the team), an absent column can cause\nsome of the rollout to enter a crashloop.\nTo avoid this, split your changes across releases, such as below.\nFor column renames:\n • Release 1: Add your new column\n • Release 2: Amend the codebase to use it instead of the old column\n • Release 3: Clean up - drop the old, deprecated column, which should not be referenced in code at this point.\nFor column drops:\n • Release 1: Update all code that uses the relevant column, so that nothing interacts with it any more.\n • Release 2: Clean up - drop the old, deprecated column.\nWith both paths, check for any custom schema or data migrations that might reference the deprecated column.\n1.3.10 Writing Views\nYou should rarely need to write a view for mozilla.org. Most pages are static and you should use the page function\ndocumented above.\nIf you need to write a view and the page is translated or translatable then it should use the l10n_utils.render()\nfunction to render the template.\nfrom lib import l10n_utils\nfrom django.views.decorators.http import require_safe\n@require_safe\ndef my_view(request):\n (continues on next page)\n1.3. Developing on Bedrock 39\nbedrock Documentation, Release 1.0\n (continued from previous page)\n # do your fancy things\n ctx = {\"template_variable\": \"awesome data\"}\n return l10n_utils.render(request, \"app/template.html\", ctx)\nMake sure to namespace your templates by putting them in a directory named after your app, so instead of tem-\nplates/template.html they would be in templates/blog/template.html if blog was the name of your app.\nThe require_safe ensures that only GET or HEAD requests will make it through to your view.\nIf you prefer to use Django’s Generic View classes we have a convenient helper for that. You can use it either to create\na custom view class of your own, or use it directly in a urls.py file.\n# app/views.py\nfrom lib.l10n_utils import L10nTemplateView\nclass FirefoxRoxView(L10nTemplateView):\n template_name = \"app/firefox-rox.html\"\n# app/urls.py\nurlpatterns = [\n # from views.py\n path(\"firefox/rox/\", FirefoxRoxView.as_view()),\n # directly\n path(\"firefox/sox/\", L10nTemplateView.as_view(template_name=\"app/firefox-sox.html\")),\n]\nThe L10nTemplateView functionality is mostly in a template mixin called LangFilesMixin which you can use with\nother generic Django view classes if you need one other than TemplateView. The L10nTemplateView already ensures\nthat only GET or HEAD requests will be served.\nVariation Views\nWe have a generic view that allows you to easily create and use a/b testing templates. If you’d like to have either separate\ntemplates or just a template context variable for switching, this will help you out. For example.\n# urls.py\nfrom django.urls import path\nfrom bedrock.utils.views import VariationTemplateView\nurlpatterns = [\n path(\"testing/\",\n VariationTemplateView.as_view(template_name=\"testing.html\",\n template_context_variations=[\"a\", \"b\"]),\n name=\"testing\"),\n]\nThis will give you a context variable called variation that will either be an empty string if no param is set, or a if\n?v=a is in the URL, or b if ?v=b is in the URL. No other options will be valid for the v query parameter and variation\nwill be empty if any other value is passed in for v via the URL. So in your template code you’d simply do the following:\n{% if variation == 'b' %}

This is the B variation of our test. Enjoy!

{% endif %}\n40 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nIf you’d rather have a fully separate template for your test, you can use the template_name_variations argument to\nthe view instead of template_context_variations.\n# urls.py\nfrom django.urls import path\nfrom bedrock.utils.views import VariationTemplateView\nurlpatterns = [\n path(\"testing/\",\n VariationTemplateView.as_view(template_name=\"testing.html\",\n template_name_variations=[\"1\", \"2\"]),\n name=\"testing\"),\n]\nThis will not provide any extra template context variables, but will instead look for alternate template names. If the\nURL is testing/?v=1, it will use a template named testing-1.html, if v=2 it will use testing-2.html, and for\neverything else it will use the default. It simply puts a dash and the variation value between the template file name and\nfile extension.\nIt is theoretically possible to use the template name and template context versions of this view together, but that would\nbe an odd situation and potentially inappropriate for this utility.\nYou can also limit your variations to certain locales. By default the variations will work for any localization of the page,\nbut if you supply a list of locales to the variation_locales argument to the view then it will only set the variation\ncontext variable or alter the template name (depending on the options explained above) when requested at one of said\nlocales. For example, the template name example above could be modified to only work for English or German like so\n# urls.py\nfrom django.urls import path\nfrom bedrock.utils.views import VariationTemplateView\nurlpatterns = [\n path(\"testing/\",\n VariationTemplateView.as_view(template_name=\"testing.html\",\n template_name_variations=[\"1\", \"2\"],\n variation_locales=[\"en-US\", \"de\"]),\n name=\"testing\"),\n]\nAny request to the page in for example French would not use the alternate template even if a valid variation were given\nin the URL.\nNote: If you’d like to add this functionality to an existing Class-Based View, there is a mixin that implements this\npattern that should work with most views: bedrock.utils.views.VariationMixin.\n1.3. Developing on Bedrock 41\nbedrock Documentation, Release 1.0\nGeo Template View\nNow that we have our CDN configured properly, we can also just swap out templates per request country. This is very\nsimilar to the above, but it will simply use the proper template for the country from which the request originated.\nfrom bedrock.base.views import GeoTemplateView\nclass CanadaIsSpecialView(GeoTemplateView):\n geo_template_names = {\n \"CA\": \"mozorg/canada-is-special.html\",\n }\n template_name = \"mozorg/everywhere-else-is-also-good.html\"\nFor testing purposes while you’re developing or on any deployment that is not accessed via the production domain\n(www.mozilla.org) you can append your URL with a geo query param (e.g. /firefox/?geo=DE) and that will take\nprecedence over the country from the request header.\nOther Geo Stuff\nThere are a couple of other tools at your disposal if you need to change things depending on the location of the user.\nYou can use the bedrock.base.geo.get_country_from_request function in a view and it will return the country\ncode for the request (either from the CDN or the query param, just like above).\nfrom bedrock.base.geo import get_country_from_request\ndef dude_view(request):\n country = get_country_from_request(request)\n if country == \"US\":\n # do a thing for the US\n else:\n # do the default thing\nThe other convenience available is that the country code, either from the CDN or the query param, is avilable in any\ntemplate in the country_code variable. This allows you to change anything about how the template renders based on\nthe location of the user.\n{% if country_code == \"US\" %}\n

GO MURICA!

\n{% else %}\n

Yay World!

\n{% endif %}\nReference:\n • Officially assigned list of ISO country codes.\n42 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.3.11 Coding Style\nBedrock uses the following open source tools to follow coding styles and conventions, as well as applying automatic\ncode formatting:\n • ruff for Python style, code quality rules, and import ordering.\n • black for Python code formatting.\n • Prettier for JavaScript code formatting.\n • ESLint for JavaScript code quality rules.\n • Stylelint for Sass/CSS style and code quality rules.\nFor front-end HTML & CSS conventions, bedrock uses Mozilla’s Protocol design system for building components.\nYou can read the Protocol documentation site for more information.\nMozilla also has some more general coding styleguides available, although some of these are now rather outdated:\n • Mozilla Python Style Guide\n • Mozilla HTML Style Guide\n • Mozilla JS Style Guide\n • Mozilla CSS Style Guide\n1.3.12 Test coverage\nWhen the Python tests are run, a coverage report is generated, showing which lines of the codebase have tests that\nexecute them, and which do not. You can view this report in your browser at file:///path/to/your/checkout/\nof/bedrock/python_coverage/index.html.\nWhen adding code, please aim to provide solid test coverage, using the coverage report as a guide. This doesn’t\nnecessarily mean every single line needs a test, and 100% coverage doesn’t mean 0% defects.\n1.3.13 Configuring your Code Editor\nBedrock includes an .editorconfig file in the root directory that you can use with your code editor to help maintain\nconsistent coding styles. Please see editorconfig.org. for a list of supported editors and available plugins.\n1.3.14 Working with Protocol Design System\nBedrock uses the Protocol Design System to quickly produce consistent, stable components. There are different meth-\nods – depending on the component – to import a Protocol component into our codebase.\nOne method involves two steps:\n 1. Adding the correct markup or importing the appropriate macro to the page’s HTML file.\n 2. Importing the necessary Protocol styles to a page’s SCSS file.\nThe other method is to import CSS bundles onto the HTML file. However, this only works for certain components,\nwhich are listed below in the respective section.\n1.3. Developing on Bedrock 43\nbedrock Documentation, Release 1.0\nStyles and Components\nThe base templates in Bedrock have global styles from Protocol that apply to every page. When we need to extend\nthese styles on a page-specific basis, we set up Protocol in a page-specific SCSS file.\nFor example, on a Firefox product page, we might want to use Firefox logos or wordmarks that do not exist on every\npage.\nTo do this, we add Protocol mzp- classes to the HTML:\n// bedrock/bedrock/firefox/templates/firefox/{specific-page}.html\n
\n Firefox Browser\n
\nThen we need to include those Protocol styles in the page’s SCSS file:\n/* bedrock/media/css/firefox/{specific-page}.scss */\n/* if we need to use protocol images, we need to set the $image-path variable */\n$image-path: '/media/protocol/img';\n/* mozilla is the default theme, so if we want a different one, we need to set the\n ˓→$brand-theme variable */\n$brand-theme: 'firefox';\n/* the lib import is always essential: it provides access to tokens, functions, mixins,␣\n ˓→and theming */\n@import '~@mozilla-protocol/core/protocol/css/includes/lib';\n/* then you add whatever specific protocol styling you need */\n@import '~@mozilla-protocol/core/protocol/css/components/logos/wordmark';\n@import '~@mozilla-protocol/core/protocol/css/components/logos/wordmark-product-firefox';\nNote: If you create a new SCSS file for a page, you will have to include it in that page’s CSS bundle by updating\nstatic-bundles.json file.\nMacros\nThe team has created several Jinja macros out of Protocol components to simplify the usage of components housing\nlarger blocks of code (i.e. Billboard). The code housing the custom macros can be found in our protocol macros file.\nThese Jinja macros include parameters that are simple to define and customize based on how the component should\nlook like on a given page.\nTo use these macros in files, we simply import a macro to the page’s HTML code and call it with the desired arguments,\ninstead of manually adding Protocol markup. We can import multiple macros in a comma-separated fashion, ending\nthe import with with context:\n// bedrock/bedrock/firefox/templates/firefox/{specific-page}.html\n{% from \"macros-protocol.html\" import billboard with context %}\n{{ billboard(\n title='This is Firefox.',\n (continues on next page)\n44 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n (continued from previous page)\n ga_title='This is Firefox',\n desc='Firefox is an awesome web browser.',\n link_cta='Click here to install',\n link_url=url('firefox.new')\n )}}\nBecause not all component styles are global, we still have to import the page-specific Protocol styles in SCSS:\n/* bedrock/media/css/firefox/{specific-page}.scss */\n$brand-theme: 'firefox';\n@import '~@mozilla-protocol/core/protocol/css/includes/lib';\n@import '~@mozilla-protocol/core/protocol/css/components/billboard';\nImport CSS Bundles\nWe created pre-built CSS bundles to be used for some components due to their frequency of use. This method only\nrequires an import into the HTML template. Since it’s a separate CSS bundle, we don’t need to import that component\nin the respective page CSS. The CSS bundle import only works for the following components:\n • Split\n • Card\n • Picto\n • Callout\n • Article\n • Newsletter form\n • Emphasis box\nInclude a CSS bundle in the template’s page_css block along with any other page-specific bundles, like so:\n{% block page_css %}\n {{ css_bundle('protocol-split') }}\n {{ css_bundle('protocol-card') }}\n {{ css_bundle('page-specific-bundle') }}\n{% endblock %}\n1.4 How to contribute\nBefore diving into code it might be worth reading through the Developing on Bedrock documentation, which contains\nuseful information and links to our coding guidelines for Python, Django, JavaScript and CSS.\n1.4. How to contribute 45\nbedrock Documentation, Release 1.0\n1.4.1 Git workflow\nWhen you want to start contributing, you should create a branch from main. This allows you to work on different\nproject at the same time:\n$ git switch main\n$ git switch -c topic-branch\nTo keep your branch up-to-date, assuming the mozilla repository is the remote called mozilla:\n$ git switch main\n$ git pull --ff-only\nMore on Why you should use –ff-only. To make this the default update your Git config as described in the article.\n$ git switch topic-branch\n$ git rebase main\nIf you need more Git expertise, a good resource is the Git book.\nOnce you’re done with your changes, you’ll need to describe those changes in the commit message.\n1.4.2 Git commit messages\nCommit messages are important when you need to understand why something was done.\n • First, learn how to write good git commit messages.\n • All commit messages must include a bug number. You can put the bug number on any line, not only the first one.\n • If you use the syntax bug xxx, Github will reference the commit into Bugzilla. With fix bug xxx, it will even\n close the bug once it goes into main.\nIf you’re asked to change your commit message, you can use these commands:\n$ git commit --amend\n-f is doing a force push because you modified the history\n$ git push -f my-remote topic-branch\n1.4.3 Submitting your work\nIn general, you should submit your work with a pull request to main. If you are working with other people or you want\nto put your work on a demo server, then you should be working on a common topic branch.\nOnce your code has been positively reviewed, it will be deployed shortly after. So if you want feedback on your code but\nit’s not ready to be deployed, you should note it in the pull request, or use a Draft PR. Also make use of an appropriate\nlabel, such as Do Not Merge.\n46 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.4.4 Squashing your commits\nShould your pull request contain more than one commit, sometimes we may ask you to squash them into a single\ncommit before merging. You can do this with git rebase.\nAs an example, let’s say your pull request contains two commits. To squash them into a single commit, you can follow\nthese instructions:\n$ git rebase -i HEAD~2\nYou will then get an editor with your two commits listed. Change the second commit from pick to fixup, then save and\nclose. You should then be able to verify that you only have one commit now with git log.\nTo push to GitHub again, because you “altered the history” of the repo by merging the two commits into one, you’ll\nhave to git push -f instead of just git push.\n1.4.5 Deploying your code\nThese are the websites that Bedrock is usually deployed to as part of development.\nDemo sites\nBedrock as a platform can run in two modes: Mozorg Mode (for content that will appear on mozilla.org) and Pocket\nMode (for content that will end up on getpocket.com).\nTo support this, we have two separate sets of URLs we use for demos. To get code up to one of those URLs, push it to\nthe specified branch on github.com/mozilla/bedrock:\n • Mozorg:\n – Branch mozorg-demo-1 -> https://www-demo1.allizom.org/\n – Branch mozorg-demo-2 -> https://www-demo2.allizom.org/\n – Branch mozorg-demo-3 -> https://www-demo3.allizom.org/\n – Branch mozorg-demo-4 -> https://www-demo4.allizom.org/\n – Branch mozorg-demo-5 -> https://www-demo5.allizom.org/\n – Branch mozorg-demo-6 -> https://www-demo6.allizom.org/\n – Branch mozorg-demo-7 -> https://www-demo7.allizom.org/\n – Branch mozorg-demo-8 -> https://www-demo8.allizom.org/\n – Branch mozorg-demo-9 -> https://www-demo9.allizom.org/\n • Pocket:\n – Branch pocket-demo-1 -> https://www-demo1.tekcopteg.com/\n – Branch pocket-demo-2 -> https://www-demo2.tekcopteg.com/\n – Branch pocket-demo-3 -> https://www-demo3.tekcopteg.com/\n – Branch pocket-demo-4 -> https://www-demo4.tekcopteg.com/\n – Branch pocket-demo-5 -> https://www-demo5.tekcopteg.com/\nFor example, for Mozorg:\n1.4. How to contribute 47\nbedrock Documentation, Release 1.0\n$ git push -f mozilla my-demo-branch:mozorg-demo-2\nOr for Pocket:\n$ git push -f mozilla my-demo-branch:pocket-demo-1\nDeployment notification and logs\nAt the moment, there is no way to view logs for the deployment unless you have access to Google Cloud Platform.\nIf you do have access, the Cloud Build dashboard shows the latest builds, and Cloud Run will link off to the relevant\nlogs.\nThere are Mozilla Slack notifications in #www-notify that show the status of demo builds. (Work is ticketed to make\nthose notifications richer in data.)\nEnv vars\nRather than tweak env vars via a web UI, they are set in config files. Both Mozorg and Pocket mode have specific\ndemo-use-only env var files, which are only used by our GCP demo setup. They are:\n • bedrock/gcp/bedrock-demos/cloudrun/mozorg-demo.env.yaml\n • bedrock/gcp/bedrock-demos/cloudrun/pocket-demo.env.yaml\nIf you need to set/add/remove an env var, you can edit the relevant file on your feature branch, commit it and push it\nalong with the rest of the code, as above. There is a small risk of clashes, but these can be best avoided if you keep up\nto date with bedrock/main and can be resolved easily.\nSecret values\nRemember that the env vars files are public because they are in the Bedrock codebase, so sensitive values should not\nbe added there, even temporarily.\nIf you need to add a secret value, this currently needs to be added at the GCP level by someone with appropriate\npermissions to edit and apply the Terraform configuration, and to edit the trigger YAML spec to pass through the new\nsecret. Currently Web-SRE and the backend team have appropriate GCP access and adding a secret is relatively quick.\n(We can make this easier in the future if there’s sufficient need, of course.)\nNote: Always-on vs auto-sleep demo servers\nThe demo servers are on GCP Cloud Run, and by default they will be turned off if there is no traffic for 15 minutes.\nAfter this time, the demo app will be woken up if it receives a request.\nNormally, a ‘cold start’ will not be a problem. However, if the branch you are demoing does things that alter the\ndatabase (i.e contains migrations), then you may find the restarted demo app crashes because the new migrations have\nnot been applied after a cold start.\nThe best current way to avoid that happening is:\n • In your branch’s demo-env-vars YAML file, set LOCAL_DB_UPDATE=True so that the Dev DB is not pulled down\n to the demo app\n • Ask one of the backend team to set the Demo app to always be awake by setting ‘Minimum instances’ to 1 for\n the relevant Cloud Run service and restarting it. The app will always be on and will not sleep, so won’t need\n a cold start. Once you have completed the feature work, please ask the backenders to restore the default sleepy\n behaviour. As an example with mozorg-demo-1:\n – To make it always-on: gcloud run services update mozorg-demo-1 --min-instances 1\n – To revert it to auto-sleeping: gcloud run services update mozorg-demo-1 --min-instances 0\n48 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n(We’ll try to make this a self-serve thing as soon as we can).\nDEPRECATED: Heroku Demo Servers\nDemos are now powered by Google Cloud Platform (GCP), and no longer by Heroku.\nHowever, the Github Action we used to push code to Heroku may still be enabled. Pushing a branch to one of the\ndemo/* branches of the mozilla/bedrock repo will trigger this. However, note that URLs that historically used to point\nto Heroku will be pointed to the new GCP demos services instead, so you will have to look at Heroku’s web UI to see\nwhat the URL of the relevant Heroku app is.\nTo push to launch a demo on Heroku:\n$ git push -f mozilla my-demo-branch:demo/1\nPushing to production\nWe’re doing pushes as soon as new work is ready to go out.\nCode flows automatically to Dev, amd manually to Stage and to Production. See Continuous Integration & Deployment\nfor details.\nAfter doing a push, those who are responsible for implementing changes need to update the bugs that have been pushed\nwith a quick message stating that the code was deployed.\nIf you’d like to see the commits that will be deployed before the push run the following command:\n$ ./bin/open-compare.py\nThis will discover the currently deployed git hash, and open a compare URL at github to the latest main. Look at\nopen-compare.py -h for more options.\nWe automate pushing to production via tagged commits (see Continuous Integration & Deployment)\n1.5 Continuous Integration & Deployment\nBedrock runs a series of automated tests as part of continuous integration workflow and deployment pipeline. You can\nlearn more about each of the individual test suites by reading their respective pieces of documentation:\n • Python unit tests (see Run the tests).\n • JavaScript unit tests (see Front-end testing).\n • Redirect tests (see Testing redirects).\n • Functional tests (see Front-end testing).\n1.5. Continuous Integration & Deployment 49\nbedrock Documentation, Release 1.0\n1.5.1 Deployed site URLs\nNote that a deployment of Bedrock will actually trigger two separate deployments: one serving all of mozilla.org\nand another serving certain parts of getpocket.com\nDev\n • Mozorg URL: https://www-dev.allizom.org/\n • Pocket Marketing pages URL: https://dev.tekcopteg.com/\n • Bedrock locales: dev repo\n • Bedrock Git branch: main, deployed on git push\nStaging\n • Mozorg URL: https://www.allizom.org/\n • Pocket Marketing pages URL: https://www.tekcopteg.com/\n • Bedrock locales: prod repo\n • Bedrock Git branch: stage, deployed on git push\nProduction\n • Mozorg URL: https://www.mozilla.org/\n • Pocket Marketing pages URL: https://getpocket.com/\n • Bedrock locales: prod repo\n • Bedrock Git branch: prod, deployed on git push with date-tag\nYou can check the currently deployed git commit by checking /revision.txt on any of these URLs.\n1.5.2 Tests in the lifecycle of a change\nBelow is an overview of the tests during the lifecycle of a change to bedrock:\nLocal development\nThe change is developed locally, and page specific integration tests can be executed against a locally running in-\nstance of the application. If testing changes to the website as a whole is required, then pushing changes to the special\nrun-integration-tests branch (see below) is much faster than running the full test suite locally.\n50 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nPull request\nOnce a pull request is submitted, a Unit Tests Github Action will run both the Python and JavaScript unit tests, as well\nas the suite of redirect headless HTTP(s) response checks.\nPush to main branch\nWhenever a change is pushed to the main branch, a new image is built and deployed to the dev environment, and the\nfull suite of headless and UI tests are run. This is handled by the pipeline, and is subject to change according to the\nsettings in the Github Action workflow defined in bedrock/.github/workflows/integration_tests.yml.\nThe tests for the dev environment are currently configured as follows:\n • Chrome (latest) via local Selenium grid.\n • Firefox (latest) via local Selenium grid.\n • Internet Explorer 11 (smoke tests) via Sauce Labs.\n • Internet Explorer 9 (sanity tests) via Sauce Labs.\n • Headless tests.\nNote that now we have Mozorg mode and Pocket mode, we actually stand up two dev, two stage and two test deployments\nand we run the appropriate integration tests against each deployment: most tests are written for Mozorg, but there are\nsome for Pocket mode that also get run.\nNote: The deployment workflow runs like this\n1. A push to the main/stage/prod/run-integration-tests branch of mozilla/bedrock triggers a webhook ping\nto the (private) mozilla-sre-deploy/deploy-bedrock repo.\n2. A Github Action (GHA) in mozilla-sre-deploy/deploy-bedrock builds a “release”-ready Bedrock container\nimage, which it stores in a private container registry (private because our infra requires container-image access to be\nlocked down). Using the same commit, the workflow also builds an equivalent set of public Bedrock container images,\nwhich are pushed to Docker Hub.\n 3. The GHA deploys the relevant container image to the appropriate environment.\n4. The GHA pings a webhook back in mozilla/bedrock to run integration tests against the environment that has just\nbeen deployed.\nPush to stage branch\nWhenever a change is pushed to the stage branch, a production docker image is built, published to Docker Hub, and\ndeployed to a public staging environment. Once the new image is deployed, the full suite of UI tests is run against it\nagain, but this time with the addition of the headless download tests.\n1.5. Continuous Integration & Deployment 51\nbedrock Documentation, Release 1.0\nPush to prod branch (tagged)\nWhen a tagged commit is pushed to the prod branch, a production container image (private, see above) is built, and\na set of public images is also built and pushed to Docker Hub if needed (usually this will have already happened as a\nresult of a push to the main or stage branch). The production image is deployed to each production deployment.\nPush to prod cheat sheet\n 1. Check out the main branch\n 2. Make sure the main branch is up to date with mozilla/bedrock main\n 3. Check that dev deployment is green:\n 1. View the Integration Tests Github Action and look at the run labelled Run Integration tests for\n main\n 4. Check that stage deployment is also green (Run Integration tests for stage)\n 5. Tag and push the deployment by running bin/tag-release.sh --push\nNote: By default the tag-release.sh script will push to the origin git remote. If you’d like for it to push to a\ndifferent remote name you can either pass in a -r or --remote argument, or set the MOZ_GIT_REMOTE environment\nvariable. So the following are equivalent:\n$ bin/tag-release.sh --push -r mozilla\n$ MOZ_GIT_REMOTE=mozilla bin/tag-release.sh --push\nAnd if you’d like to just tag and not push the tag anywhere, you may omit the --push parameter.\n1.5.3 What Is Currently Deployed?\nYou can look at the git log of the main branch to find the last commit with a date-tag on it (e.g. 2022-05-05): this\ncommit will be the last one that was deployed to production. You can also use the whatsdeployed.io service to get a\nnice view of what is actually currently deployed to Dev, Stage, and Prod:\n1.5.4 Instance Configuration & Switches\nWe have a separate repo for configuring our primary instances (dev, stage, and prod). The docs for updating configu-\nrations in that repo are on their own page, but there is a way to tell what version of the configuration is in use on any\nparticular instance of bedrock. You can go to the /healthz-cron/ URL on an instance (see prod for example) to see\nthe current commit of all of the external Git repos in use by the site and how long ago they were updated. The info\non that page also includes the latest version of the database in use, the git revision of the bedrock code, and how long\nago the database was updated. If you recently made a change to one of these repos and are curious if the changes have\nmade it to production, this is the URL you should check.\n52 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.5.5 Updating Selenium\nThere are several components for Selenium, which are independently versioned. The first is the Python client, and this\ncan be updated via the test dependencies. The other components are the Selenium versions used in both SauceLabs and\nthe local Selenium grid. These versions are selected automatically based on the required OS / Browser configuration,\nso they should not need to be updated or specified independently.\n1.5.6 Adding test runs\nTest runs can be added by creating a new job in bedrock/.github/workflows/integration_tests.yml with the\ndesired variables and pushing that branch to Github. For example, if you wanted to run the smoke tests in IE10 (using\nSaucelabs) you could add the following clause to the matrix:\n- LABEL: test-ie10-saucelabs\n BROWSER_NAME: internet explorer\n BROWSER_VERSION: \"10.0\"\n DRIVER: SauceLabs\n PYTEST_PROCESSES: \"8\"\n PLATFORM: Windows 8\n MARK_EXPRESSION: smoke\nYou can use Sauce Labs platform configurator to help with the parameter values.\n1.5.7 Pushing to the integration tests branch\nIf you have commit rights to our Github repo (mozilla/bedrock) you can simply push your branch to the branch named\nrun-integration-tests, and the app will be deployed and the full suite of integration tests for that branch will be\nrun. Please announce in our Slack channel (#www on mozilla.slack.com) that you’ll be doing this so that we don’t get\nconflicts. Also remember that you’ll likely need to force push, as there may be commits on that branch which aren’t in\nyours – so, if you have the mozilla/bedrock remote set as mozilla:\n$ git push -f mozilla $(git branch --show-current):run-integration-tests\n1.6 Front-end testing\nBedrock runs a suite of front-end Jasmine behavioral/unit tests, which use Karma as a test runner. We also have a suite\nof functional tests using Selenium and pytest. This allows us to emulate users interacting with a real browser. All these\ntest suites live in the tests directory.\nThe tests directory comprises of:\n • /functional contains pytest tests.\n • /pages contains Python page objects.\n • /unit contains the Jasmine tests and Karma config file.\n1.6. Front-end testing 53\nbedrock Documentation, Release 1.0\n1.6.1 Installation\nFirst follow the installation instructions for bedrock, which will install the dependencies required to run the various\nfront-end test suites.\n1.6.2 Running Jasmine tests using Karma\nTo perform a single run of the Jasmine test suite using Firefox and Chrome, first make sure you have both browsers\ninstalled locally, and then activate your bedrock virtual env.\n$ pyenv activate bedrock\nYou can then run the tests with the following command:\n$ npm run test\nThis will run all our front-end linters and formatting checks before running the Jasmine test suite. If you only want to\nrun the tests themselves, you can run:\n$ npm run karma\nSee the Jasmine documentation for tips on how to write JS behavioral or unit tests. We also use Sinon for creating test\nspies, stubs and mocks.\n1.6.3 Running functional tests\nNote: Before running the functional tests, please make sure to follow the bedrock installation docs, including the\ndatabase sync that is needed to pull in external data such as event/blog feeds etc. These are required for some of the\ntests to pass. To run the tests using Firefox, you must also first download geckodriver and make it available in your\nsystem path. You can alternatively specify the path to geckodriver using the command line (see the pytest-selenium\ndocumentation for more information).\nTo download geckodriver and have it ready to run in your system, there are a couple of ways:\n • Download its latest release and add it to your system path:\n cd /path/to/your/downloaded/files/\n mv geckodriver /usr/local/bin/\n • If you’re on MacOS, download it directly using Homebrew, which automatically places it in your system path:\n brew install geckodriver\nTo run the full functional test suite against your local bedrock instance in Mozorg mode:\n$ py.test --base-url http://localhost:8000 --driver Firefox --html tests/functional/\n ˓→results.html tests/functional/\nThis will run all test suites found in the tests/functional directory and assumes you have bedrock running at\nlocalhost on port 8000. Results will be reported in tests/functional/results.html.\nTo run the full functional test suite against your local bedrock instance in Pocket mode, things are slightly different,\nbecause of the way things are set up in order to allow CI to test both Mozorg Mode and Pocket Mode at the same time.\n54 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nYou need to define a temporary environment variable (needed by the pocket_base_url fixture) and scope pytest to only\nrun Pocket tests:\n$ BASE_POCKET_URL=http://localhost:8000 py.test -m pocket_mode --driver Firefox --html␣\n ˓→tests/functional/results.html tests/functional/\nThis will run all test suites found in the tests/functional directory that have the pytest “mark” of pocket_mode and\nassumes you have bedrock running in Pocket mode at localhost on port 8000. Results will be reported in tests/\nfunctional/results.html.\nNote: If you omit the --base-url command line option in Mozorg mode (ie, not in Pocket mode) then a local instance\nof bedrock will be started, however the tests are not currently able to run against bedrock in this way.\nBy default, tests will run one at a time. This is the safest way to ensure predictable results, due to bug 1230105. If you\nwant to run tests in parallel (this should be safe when running against a deployed instance), you can add -n auto to\nthe command line. Replace auto with an integer if you want to set the maximum number of concurrent processes.\nNote: There are some functional tests that do not require a browser. These can take a long time to run, especially if\nthey’re not running in parallel. To skip these tests, add -m 'not headless' to your command line.\nTo run a single test file you must tell py.test to execute a specific file e.g. tests/functional/test_newsletter.py:\n$ py.test --base-url http://localhost:8000 --driver Firefox --html tests/functional/\n ˓→results.html tests/functional/firefox/new/test_download.py\nTo run a single test you can filter using the -k argument supplied with a keyword e.g. -k\ntest_download_button_displayed:\n$ py.test --base-url http://localhost:8000 --driver Firefox --html tests/functional/\n ˓→results.html tests/functional/firefox/new/test_download.py -k test_download_button_\n ˓→displayed\nYou can also easily run the tests against any bedrock environment by specifying the --base-url argument. For\nexample, to run all functional tests against dev:\n$ py.test --base-url https://www-dev.allizom.org --driver Firefox --html tests/\n ˓→functional/results.html tests/functional/\nNote: For the above commands to work, Firefox needs to be installed in a predictable location for your operating\nsystem. For details on how to specify the location of Firefox, or running the tests against alternative browsers, refer to\nthe pytest-selenium documentation.\nFor more information on command line options, see the pytest documentation.\n1.6. Front-end testing 55\nbedrock Documentation, Release 1.0\nRunning tests in Sauce Labs\nYou can also run tests in Sauce Labs directly from the command line. This can be useful if you want to run tests against\nInternet Explorer when you’re on Mac OSX, for instance.\n 1. Sign up for an account at https://saucelabs.com/opensauce/.\n 2. Log in and obtain your Remote Access Key from user settings.\n 3. Run a test specifying SauceLabs as your driver, and pass your credentials.\nFor example, to run the home page tests using Internet Explorer via Sauce Labs:\n$ SAUCELABS_USERNAME=thedude SAUCELABS_API_KEY=123456789 SAUCELABS_W3C=true SELENIUM_\n ˓→EXCLUDE_DEBUG=logs py.test --base-url https://www-dev.allizom.org --driver SauceLabs --\n ˓→capability browserName 'internet explorer' --capability platformName 'Windows 10' --\n ˓→html tests/functional/results.html tests/functional/test_home.py\n1.6.4 Writing Selenium tests\nTests usually consist of interactions and assertions. Selenium provides an API for opening pages, locating elements,\ninteracting with elements, and obtaining state of pages and elements. To improve readability and maintainability of the\ntests, we use the Page Object model, which means each page we test has an object that represents the actions and states\nthat are needed for testing.\nWell written page objects should allow your test to contain simple interactions and assertions as shown in the following\nexample:\ndef test_sign_up_for_newsletter(base_url, selenium):\n page = NewsletterPage(base_url, selenium).open()\n page.type_email('noreply@mozilla.com')\n page.accept_privacy_policy()\n page.click_sign_me_up()\n assert page.sign_up_successful\nIt’s important to keep assertions in your tests and not your page objects, and to limit the amount of logic in your page\nobjects. This will ensure your tests all start with a known state, and any deviations from this expected state will be\nhighlighted as potential regressions. Ideally, when tests break due to a change in bedrock, only the page objects will\nneed updating. This can often be due to an element needing to be located in a different way.\nPlease take some time to read over the Selenium documentation for details on the Python client API.\nDestructive tests\nBy default all tests are assumed to be destructive, which means they will be skipped if they’re run against a sensitive\nenvironment. This prevents accidentally running tests that create, modify, or delete data on the application under test.\nIf your test is nondestructive you will need to apply the nondestructive marker to it. A simple example is shown\nbelow, however you can also read the pytest markers documentation for more options.\nimport pytest\n@pytest.mark.nondestructive\ndef test_newsletter_default_values(base_url, selenium):\n page = NewsletterPage(base_url, selenium).open()\n assert '' == page.email\n (continues on next page)\n56 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n (continued from previous page)\n assert 'United States' == page.country\n assert 'English' == page.language\n assert page.html_format_selected\n assert not page.text_format_selected\n assert not page.privacy_policy_accepted\nSmoke tests\nSmoke tests are considered to be our most critical tests that must pass in a wide range of web browsers, including\nInternet Explorer 11. The number of smoke tests we run should be enough to cover our most critical pages where\nlegacy browser support is important.\nimport pytest\n@pytest.mark.smoke\n@pytest.mark.nondestructive\ndef test_download_button_displayed(base_url, selenium):\n page = DownloadPage(selenium, base_url, params='').open()\n assert page.is_download_button_displayed\nYou can run smoke tests only by adding -m smoke when running the test suite on the command line.\nWaits and Expected Conditions\nOften an interaction with a page will cause a visible response. While Selenium does its best to wait for any page loads\nto be complete, it’s never going to be as good as you at knowing when to allow the test to continue. For this reason, you\nwill need to write explicit waits in your page objects. These repeatedly execute code (a condition) until the condition\nreturns true. The following example is probably the most commonly used, and will wait until an element is considered\ndisplayed:\nfrom selenium.webdriver.support import expected_conditions as expected\nfrom selenium.webdriver.support.ui import WebDriverWait as Wait\nWait(selenium, timeout=10).until(\n expected.visibility_of_element_located(By.ID, 'my_element'))\nFor convenience, the Selenium project offers some basic expected conditions, which can be used for the most common\ncases.\n1.6.5 Debugging Selenium\nDebug information is collected on failure and added to the HTML report referenced by the --html argument. You can\nenable debug information for all tests by setting the SELENIUM_CAPTURE_DEBUG environment variable to always.\n1.6. Front-end testing 57\nbedrock Documentation, Release 1.0\n1.6.6 Guidelines for writing functional tests\n • Try and keep tests organized and cleanly separated. Each page should have its own page object and test file, and\n each test should be responsible for a specific purpose, or component of a page.\n • Avoid using sleeps - always use waits as mentioned above.\n • Don’t make tests overly specific. If a test keeps failing because of generic changes to a page such as an image\n filename or href being updated, then the test is probably too specific.\n • Avoid string checking as tests may break if strings are updated, or could change depending on the page locale.\n • When writing tests, try and run them against a staging or demo environment in addition to local testing. It’s also\n worth running tests a few times to identify any intermittent failures that may need additional waits.\nSee also the Web QA style guide for Python based testing.\n1.6.7 Testing Basket email forms\nWhen writing functional tests for front-end email newsletter forms that submit to Basket, we have some special case\nemail addresses that can be used just for testing:\n 1. Any newsletter subscription request using the email address “success@example.com” will always return success\n from the basket client.\n 2. Any newsletter subscription request using the email address “failure@example.com” will always raise an excep-\n tion from the basket client.\nUsing the above email addresses enables newsletter form testing without actually hitting the Basket instance, which\nreduces automated newsletter spam and improves test reliability due to any potential network flakiness.\n1.6.8 Headless tests\nThere are targeted headless tests for the download pages. These tests and are run as part of the pipeline to ensure that\ndownload links constructed via product details are well formed and return valid 200 responses.\n1.7 Managing Redirects\nWe have a redirects app in bedrock that makes it easier to add and manage redirects. Due to the size, scope, and history\nof mozilla.org we have quite a lot of redirects. If you need to add or manage redirects read on.\n1.7.1 Add a redirect\nYou should add redirects in the app that makes the most sense. For example, if the source URL is /firefox/... then\nthe bedrock.firefox app is the best place. Redirects are added to a redirects.py file within the app. If the app\nyou want to add redirects to doesn’t have such a file, you can create one and it will automatically be discovered and\nused by bedrock as long as said app is in the INSTALLED_APPS setting (see bedrock/mozorg/redirects.py as an\nexample).\nOnce you decide where it should go you can add your redirect. To do this you simply add a call to the bedrock.\nredirects.util.redirect helper function in a list named redirectpatterns in redirects.py. For example:\n58 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nfrom bedrock.redirects.util import redirect\nredirectpatterns = [\n redirect(r'^rubble/barny/$', '/flintstone/fred/'),\n]\nThis will make sure that requests to /rubble/barny/ (or with the locale like /pt-BR/rubble/barny/) will get a\n301 response sending users to /flintstone/fred/.\nThe redirect() function has several options. Its signature is as follows:\ndef redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None,\n query=None, vary=None, cache_timeout=12, decorators=None):\n \"\"\"\n Return a url matcher suited for urlpatterns.\n pattern: the regex against which to match the requested URL.\n to: either a url name that `reverse` will find, a url that will simply be returned,\n or a function that will be given the request and url captures, and return the\n destination.\n permanent: boolean whether to send a 301 or 302 response.\n locale_prefix: automatically prepend `pattern` with a regex for an optional locale\n in the URL. This locale (or None) will show up in captured kwargs as 'locale'.\n anchor: if set it will be appended to the destination URL after a '#'.\n name: if used in a `urls.py` the redirect URL will be available as the name\n for use in calls to `reverse()`. Does _NOT_ work if used in a `redirects.py` file.\n query: a dict of query params to add to the destination URL.\n vary: if you used an HTTP header to decide where to send users you should include␣\n ˓→that\n header's name in the `vary` arg.\n cache_timeout: number of hours to cache this redirect. just sets the proper `cache-\n ˓→control`\n and `expires` headers.\n decorators: a callable (or list of callables) that will wrap the view used to␣\n ˓→redirect\n the user. equivalent to adding a decorator to any other view.\n Usage:\n urlpatterns = [\n redirect(r'projects/$', 'mozorg.product'),\n redirect(r'^projects/seamonkey$', 'mozorg.product', locale_prefix=False),\n redirect(r'apps/$', 'https://marketplace.firefox.com'),\n redirect(r'firefox/$', 'firefox.new', name='firefox'),\n redirect(r'the/dude$', 'abides', query={'aggression': 'not_stand'}),\n ]\n \"\"\"\n1.7. Managing Redirects 59\nbedrock Documentation, Release 1.0\n1.7.2 Differences\nThis all differs from urlpatterns in urls.py files in some important ways. The first is that these happen first. If\nsomething matches in a redirects.py file it will always win the race if another URL in a urls.py file would also have\nmatched. Another is that these are matched before any locale prefix stuff happens. So what you’re matching against in\nthe redirects files is the original URL that the user requested. By default (unless you set locale_prefix=False) your\npatterns will match either the plain URL (e.g. /firefox/os/) or one with a locale prefix (e.g. /fr/firefox/os/). If\nyou wish to include this locale in the destination URL you can simply use python’s string format() function syntax. It is\npassed to the format method as the keyword argument locale (e.g. redirect('^stuff/$', '{locale}whatnot/\n')). If there was no locale in the URL the {locale} substitution will be an empty string. Similarly if you wish\nto include a part of the original URL in the destination, just capture it with the regex using a named capture (e.g.\nr'^stuff/(?P.*)$' will let you do '/whatnot/{rest}').\n1.7.3 Utilities\nThere are a couple of utility functions for use in the to argument of redirect that will return a function to allow you\nto match something in an HTTP header.\nua_redirector\nbedrock.redirects.util.ua_redirector is a function to be used in the to argument that will use a regex to\nmatch against the User-Agent HTTP header to allow you to decide where to send the user. For example:\nfrom bedrock.redirects.util import redirect, ua_redirector\nredirectpatterns = [\n redirect(r'^rubble/barny/$',\n ua_redirector('firefox(os)?', '/firefox/', '/not-firefox/'),\n cache_timeout=0),\n]\nYou simply pass it a regex to match, the destination URL (substitutions from the original URL do work) if the regex\nmatches, and another destination URL if the regex does not match. The match is not case sensitive unless you add the\noptional case_sensitive=True argument.\nNote: Be sure to include the cache_timeout=0 so that you won’t be bitten by any caching proxies sending all users\none way or the other. Do not set the Vary: User-Agent header; this will not work in production.\nheader_redirector\nThis is basically the same as ua_redirector but works against any header. The arguments are the same as above\nexcept that thre is an additional first argument for the name of the header:\nfrom bedrock.redirects.util import redirect, header_redirector\nredirectpatterns = [\n redirect(r'^rubble/barny/$',\n header_redirector('cookie', 'been-here', '/firefox/', '/firefox/new/'),\n (continues on next page)\n60 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n (continued from previous page)\n vary='cookie'),\n]\n1.7.4 Testing redirects\nA suite of tests exists for redirects, which is intended as a reference of the redirects we expect to work on\nwww.mozilla.org. This will become a base for implementing these redirects in the bedrock app and allow us to test\nthem before release.\nInstallation\nFirst follow the installation instructions for bedrock, which will guide you through installing pip and setting up a virtual\nenvironment for the tests. The additional requirements can then be installed by using the following commands:\n$ source venv/bin/activate\n$ pip install -r requirements/dev.txt\nRunning the tests\nIf you wish to run the full set of tests, which requires a deployed instance of the site (e.g. www.mozilla.org) you can\nset the --base-url command line option:\n$ py.test --base-url https://www.mozilla.org tests/redirects/\nBy default, tests will run one at a time. If you intend to run the suite against a remote instance of the site (e.g. production)\nit will run a lot quicker by running the tests in parallel. To do this, you can add -n auto to the command line. Replace\nauto with an integer if you want to set the maximum number of concurrent processes.\n1.8 Newsletters\nBedrock includes support for signing up for and managing subscriptions and preferences for Mozilla newsletters.\nMany pages have a form to sign-up for the default newsletters, “Mozilla Foundation” and “Firefox & You”. Other pages\nhave more specific sign up forms, such as the contribute page, or Mozilla VPN wait-list page.\n1.8.1 Features\n • Ability to subscribe to a newsletter from a web form. Many pages on the site might include this form.\n • Whole pages devoted to subscribing to one newsletter, often with custom text, branding, and layout.\n • Newsletter preference center - allow user to change their email preferences (e.g. language, HTML vs. text), as\n well as which newsletters they’re subscribed to, etc. Access is limited by requiring a user-specific token in the\n URL (it’s a UUID). The full URL is included as a link in each newsletter sent to the user. Users can also recover\n a link to their token by visiting the newsletter recovery page and entering their email address.\n1.8. Newsletters 61\nbedrock Documentation, Release 1.0\n1.8.2 Newsletters\nNewsletters have a variety of characteristics. Some of these are implemented in Bedrock, others are transparent to\nBedrock but implemented in the basket back-end that provides our interface to the newsletter vendor.\n • Public name - the name that is displayed to users, e.g. “Firefox Weekly Tips”.\n • Internal name - a short string that is used internal to Bedrock and basket to identify a newsletter. Typically these\n are lowercase strings of words joined by hyphens, e.g. “firefox-tips”. This is what we send to basket to identify\n a newsletter, e.g. to subscribe a user to it.\n • Show publicly - pages like the newsletter preferences center show a list of unsubscribed newsletters and allow\n subscribing to them. Some newsletters aren’t included in that list by default (though they are shown if the user is\n already subscribed, to let them unsubscribe). If the user has a Firefox Account, there are also some other related\n newsletters that will always be shown in the list.\n • Languages - newsletters are available in a particular set of languages. Typically when subscribing to a newsletter,\n a user can choose their preferred language. We should try not to let them subscribe to a newsletter in a language\n that it doesn’t support.\n The backend only stores one language for the user though, so whenever the user submits one of our forms,\n whatever language they last submitted is what is saved for their preference for everything.\n • Welcome message - each newsletter can have a canned welcome message that is sent to a user when they subscribe\n to it. Newsletters should have both an HTML and a text version of this.\n • Drip campaigns - some newsletters implement so-called drip campaigns, in which a series of canned messages\n are dribbled out to the user over a period of time. E.g. 1 week after subscribing, they might get message 1; a\n week later, message 2, and so on until all the canned messages have been sent.\n Because drip campaigns depend on the sign-up date of the user, we’re careful not to accidentally change the\n sign-up date, which could happen if we sent redundant subscription commands to our backend.\n1.8.3 Bedrock and Basket\nBedrock is the user-facing web application. It presents an interface for users to subscribe and manage their subscriptions\nand preferences. It does not store any information. It gets all newsletter and user-related information, and makes up-\ndates, via web requests to the Basket server. These requests are made typically made by Bedrock’s front-end JavaScript\nmodules.\nThe Basket server implements an HTTP API for the newsletters. The front-end (Bedrock) can make calls to it to retrieve\nor change users’ preferences and subscriptions, and information about the available newsletters. Basket implements\nsome of that itself, and other functions by calling the newsletter vendor’s API. Details of that are outside the scope of\nthis document, but it’s worth mentioning that both the user token (UUID) and the newsletter internal name mentioned\nabove are used only between Bedrock and Basket.\nSee the Basket docs for more information.\n62 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.8.4 URLs\nHere are a few important mozorg newsletter URLs. Some of these were established before Bedrock came along, and\nso are unlikely to be changed.\n • /newsletter/ - Subscribe to ‘mozilla-and-you’ newsletter (public name: “Firefox & You”)\n • /newsletter/existing/{USERTOKEN}/ - User management of their preferences and subscriptions.\n • /newsletter/confirm/{USERTOKEN}/ - URL someone lands on when they confirm their email address after\n initially subscribing.\n • /newsletter/country/{USERTOKEN}/ - Allows users to change their country.\n • /newsletter/recovery/ - Allows users to recover a link containing their token so they can manage their\n subscriptions.\n • /newsletter/updated/ - A page users are redirected to after updating their details, or unsubscribing.\nNote: URLs that contain {USERTOKEN} will have their path rewritten on page load so that they no longer contain the\ntoken e.g. /newsletter/existing/{USERTOKEN}/ will be rewritten to just /newsletter/existing/. This helps\nto prevent accidental sharing of user tokens in URLS and also against referral information leakage.\n1.8.5 Footer sign-up\nIn some common templates, you can customize the footer sign-up form by overriding the email_form template block.\nFor example, to have no sign-up form:\n{% block email_form %}{% endblock %}\nThe default is:\n{% block email_form %}{{ email_newsletter_form() }}{% endblock %}\nThis will render a sign-up for “Firefox & You”. You can pass parameters to the macro email_newsletter_form\nto change that. For example, the newsletters parameter controls which newsletter is signed up for, and title can\noverride the text:\n{% block email_form %}\n {{ email_newsletter_form('app-dev',\n 'Sign up for more news about the Firefox Marketplace.') }}\n{% endblock %}\nThe newsletters parameter, the first positional argument, can be either a list of newsletter IDs or a comma separated list\nof newsletters IDs:\n{% block email_form %}\n {{ email_newsletter_form('mozilla-foundation, mozilla-and-you') }}\n{% endblock %}\nPages can control whether country or language fields are included by passing include_language=[True|False]\nand/or include_country=[True|False].\n1.8. Newsletters 63\nbedrock Documentation, Release 1.0\n1.9 Contentful CMS (Content Management System) Integration\n1.9.1 Overview\nContentful is a headless CMS. It stores content for our website in a structured format. We request the content from\nContentful using an API. Then the content gets made into Protocol components for display on the site.\nWe define the structure Contentful uses to store the data in content models. The content models are used to create a\nform for editors to fill out when they want to enter new content. Each chunk of content is called an entry.\nFor example: we have a content model for our “card” component. That model creates a form with fields like heading,\nlink, blurb, and image. Each card that is created from the model is its own entry.\nWe have created a few different types of content models. Most are components that correspond to components in our\ndesign system. The smallest create little bits of code like buttons. The larger ones group together several entries for the\nsmaller components into a bigger component or an entire page.\nFor example: The Page: General model allows editors to include a hero entry, body entry, and callout entry. The\ncallout layout entry, in turn, includes a CTA (Call To Action) entry.\nOne advantage of storing the content in small chunks like this is that is can be reused in many different pages. A callout\nwhich focuses on the privacy related reasons to download Firefox could end up on the Private Browsing, Ad Tracker\nBlocking, and Fingerprinter Blocking pages. If our privacy focused tagline changes from “Keep it secret with Firefox”\nto “Keep it private with Firefox” it only needs to be updated in one entry.\nSo, when looking at a page on the website that comes from Contentful you are typically looking at several different\nentries combined together.\nOn the bedrock side, the data for all entries is periodically requested from the API and stored in a database.\nWhen a Contentful page is requested the code in api.py transforms the information from the database into a group of\nPython dictionaries (these are like key/value pairs or an object in JS).\nThis data is then passed to the page template (either Mozilla or for Firefox themed as appropriate). The page template\nincludes some files which take the data and feed it into macros to create Protocol components. These are the same\nmacros we use on non-Contentful pages. There are also includes which will import the appropriate JS and CSS files\nto support the components.\nOnce rendered the pages get cached on the CDN as usual.\n1.9.2 Contentful Apps\nInstalled on Environment level. Make sure you are in the environment you want to edit before accessing an app. Use\nApps link in top navigation of Contentful Web App to find an environment’s installed apps.\nCompose\nCompose provides a nicer editing experience. It creates a streamlined view of pages by combining multiple entries into\na single edit screen and allowing field groups for better organization.\nAny changes made to Compose page entries in a specific environment are limited to that environment. If you are in a\nsandbox environment, you should see an /environments/sandbox-name path at the end of your Compose URL.\n64 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nKnown Limitations\n • Comments are not available on Compose entries\n • It is not possible to edit embedded entries in Rich Text fields in Compose app. Selecting the “edit” option in the\n dropdown opens the entry in the Contentful web app.\nMerge\nMerge provides a UI for comparing the state of Content Models across two environments. You can select what changes\nyou would like to migrate to a new environment.\nKnown Limitations\n • Does not migrate Help Text (under Appearance Tab)\n • Does not migrate any apps used with those Content Models\n • Does not migrate Content Entries or Assets\n • It can identify when Content Models should be available in Compose, but it cannot migrate the field groups\nOthers\n • Launch allows creation of “releases”, which can help coordinate publishing of multiple entries\n • Workflows standardizes process for a specific Content Model. You can specify steps and permissions to regulate\n how content moves from draft to published.\n1.9.3 Content Models\nEmoji legend for content models\n • this component is a page, it will include meta data for the page, a folder, and slug\n • this is a layout wrapper for another component\n • this component includes editable content, not just layout config\n • this component is suitable for inclusion as an inline entry in a rich text field\n • this component can be embedded without a layout wrapper\nNaming conventions for content models\nNote: For some fields it is important to be consistent because of how they are processed in bedrock. For all it is\nimportant to make the editor’s jobs easier.\nName\n This is for the internal name of the entry. It should be set as the Entry title, required, and unique.\n1.9. Contentful CMS (Content Management System) Integration 65\nbedrock Documentation, Release 1.0\nPreview (and Preview Title, Preview Blurb, Preview Image)\n These will be used in search results and social media sites. There’s also the potential to use them for aggregate\n pages on our own sites. Copy configuration and validation from an existing page.\nHeading (and Heading Level)\n Text on a page which provides context for information that follows it. Usually made into a H1-H4 in bedrock.\n Not: header, title, or name.\nImage (and Image Size, Image Width)\n Not: picture, photo, logo, or icon (unless we are specifically talking about a logo or icon.)\nContent\n Multi-reference\nProduct Icon\n Copy configuration and validation from an existing page.\nTheme\n Copy configuration and validation from an existing page.\nBody (Body Width, Body Vertical Alignment, Body Horizontal Alignment)\n Rich text field in a Component. Do not use this for multi reference fields, even if the only content on the page is\n other content entries. Do not use MarkDown for body fields, we can’t restrict the markup. Copy configuration\n and validation from an existing page.\nRich Text Content\n Rich text field in a Compose Page\nCTA\n The button/link/dropdown that we want a user to interact with following some content. Most often appearing in\n Split and Callout components.\nPage\nPages in bedrock are created from page entries in Contentful’s Compose App.\nHomepage\n The homepage needs to be connected to bedrock using a Connect component (see Legacy) and page meta data\n like title, blurb, image, etc come from bedrock.\nGeneral\n Includes hero, text, and callout. The simplified list and order of components is intended to make it easier for\n editors to put a page together.\nVersatile\n No pre-defined template. These pages can be constructed from any combination of layout and component entries.\nResource Center\n Includes product, category, tags, and a rich text editor. These pages follow a recognizable format that will help\n orient users looking for more general product information (i.e. VPN).\nThe versatile and general templates do not need bedrock configuration to be displayed. Instead, they should appear\nautomatically at the folder and slug specified in the entry. These templates do include fields for meta data.\n66 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nLayout\nThese entries bring a group of components together. For example: 3 picto blocks in a picto block layout. They also\ninclude layout and theme options which are applied to all of the components they bring together. For example: centering\nthe icons in all 3 picto blocks.\nThese correspond roughly to Protocol templates.\nThe one exception to the above is the Layout: Large Card, which exists to attach a large display image to a regular card\nentry. The large card must still be included in the Layout: 5 Cards.\nComponent\nWe’re using this term pretty loosely. It corresponds roughly to a Protocol atom, molecule, or organism.\nThese entries include the actual content, the bits that people write and the images that go with it.\nIf they do not require a layout wrapper there may also be some layout and theme options. For example, the text\ncomponents include options for width and alignment.\nEmbed\nThese pre-configured content pieces can go in rich text editors when allowed (picto, split, multi column text. . . ).\nEmbeds are things like logos, where we want tightly coupled style and content that will be consistent across entries. If\na logo design changes, we only need to update it in one place, and all uses of that embed will be updated.\nAdding a new Page\n • Create the content model\n – Ensure the content model name starts with page (i.e. pageProductJournalismStory)\n – Add an SEO reference field which requires the SEO Metadata content type\n – In Compose, go to Page Types and click “Manage Page Types” to make your new content model available\n to the Compose editor.\n ∗ If you have referenced components, you can choose whether they will be displayed as expanded by\n default.\n ∗ Select “SEO” field for “Page Settings” field\n – If the page is meant to be localised, ensure all fields that need localisation have the “Enable localization of\n this field” checkbox checked in content model field settings\n • Update bedrock/contentful/constants\n – Add content type constant\n – Add constant to default array\n – If page is for a single locale only, add to SINGLE_LOCALE_CONTENT_TYPES\n – If page is localised, add to LOCALISATION_COMPLETENESS_CHECK_CONFIG with an array of lo-\n calised fields that need to be checked before the page’s translation can be considered complete\n • Update bedrock/contentful/api.py\n – If you’re adding new embeddable content types, expand list of renderer helpers configured for the RichTex-\n tRenderer in the ContentfulAPIWrapper\n1.9. Contentful CMS (Content Management System) Integration 67\nbedrock Documentation, Release 1.0\n – Update ContentfulAPIWrapper.get_content() to have a clause to handle the new page type\n • Create a custom view to pass the Contentful data to a template\nAdding a new Component\nExample: Picto\n 1. Create the content model in Contentful.\n • Follow the naming conventions.\n • You may need two models if you are configuring layout separately.\n 2. Add the new content model to the list of allowed references in other content models (At the moment this is just\n the “content” reference field on pages).\n 3. In bedrock create CSS and JS entries in static-bundles for the new component.\n 4. In api.py write a def for the component.\n 5. In api.py add the component name, def, and bundles to the CONTENT_TYPE_MAP.\n 6. Find or add the macro to macros-protocol.\n 7. Import the macro into all.html and add a call to it in the entries loop.\nNote: Tips:\n • can’t define defaults in Contentful, so set those in your Python def.\n • for any optional fields make sure you check the field exists before referencing the content.\nAdding a new Embed\nExample: Wordmark.\n 1. Create the content model in Contentful.\n • Follow the naming conventions.\n 2. Add the new content model to rich text fields (like split and text).\n 3. In bedrock include the CSS in the Sass file for any component which may use it (yeah, this is not ideal, hopefully\n we will have better control in the future).\n 4. Add a def to api.py to render the piece (like _make_wordmark).\nNote: Tips:\n • can’t define defaults in Contentful, so set those in your Python def.\n • for any optional fields make sure you check the field exists before referencing the content.\n68 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nAdding a rich text field in a component\nDisable everything then enable: B, I, UL, OL, Link to URL, and Inline entry. You will want to enable some some\nHeadings as well, H1 should be enabled very rarely. Enable H2-H4 using your best judgement.\n1.9.4 Adding support for a new product icon, size, folder\nMany content models have drop downs with identical content. For example: the Hero, Callout, and Wordmark models\nall include a “product icon”. Other common fields are width and folder.\nThere are two ways to keep these lists up to date to reflect Protocol updates:\n 1. By opening and editing the content models individually in Contentful\n 2. Scripting updates using the API\nAt the moment it’s not too time consuming to do by hand, just make sure you are copy and pasting to avoid introducing\nspelling errors.\nWe have not tried scripting updates with the API yet. One thing to keep in mind if attempting this is that not all widths\nare available on all components. For example: the “Text: Four columns” component cannot be displayed in small\ncontent widths.\n1.9.5 Rich Text Rendering\nContentful provides a helper library to transform the rich text fields in the API into HTML content.\nIn places were we disagree with the rendering or want to enhance the rendering we can provide our own renderers on the\nbedrock side. They can be as simple as changing tags to tags or as complex as inserting a component.\nA list of our custom renderers is passed to the RichTextRenderer helper at the start of the ContentfulPage class in api.py.\nThe renderers themselves are also defined in api.py\nNote:\n • Built-in nodes cannot be extended or customized: Custom node types and marks are not allowed. Embed entry\n types are required to extend rich text functionality. (i.e. if you need more than one style of blockquote)\n1.9.6 L10N\nSmartling - our selected approach\nWhen setting up a content model in Contentful, fields can be designated as available for translation.\nIndividual users can be associated with different languages, so when they edit entries they see duplicate fields for each\nlanguage they can translate into. In addition - and in the most common case - these fields are automatically sent to\nSmartling to be translated there.\nOnce text for translation lands in Smartling, it is batched up into jobs for human translation. When the work is complete,\nSmartling automatically updates the relevant Contentful entries with the translations, in the appropriate fields.\nNote that those translations are only visible in Contentful if you select to view that locale’s fields, but if they are present\nin Contentful’s datastore (and that locale is enabled in the API response) they will be synced down by Bedrock.\nOn the Bedrock side, the translated content is pulled down the same way as the default locale’s content is, and is stored\nin a locale-specific ContentfulEntry in the database.\n1.9. Contentful CMS (Content Management System) Integration 69\nbedrock Documentation, Release 1.0\nIn terms of ‘activation’, or “Do we have all the parts to show this Contentful content”?, Contentful content is not\nevaluated in the same way as Fluent strings (where we will show a page in a given locale if 80% of its Fluent strings\nhave been translated, falling back to en-US where not).\nInstead, we check that all of the required fields present in the translated Entry have non-null data, and if so, then the\nentire page is viable to show in the given locale. (ie, we look at fields, not strings. It’s a coarser level of granularity\ncompared to Fluent, because the data is organised differently - most of Contentful-sourced content will be rich text, not\nindividual strings).\nThe check about whether or not a Contentful entry is ‘active’ or ‘localisation complete’ happens during the main sync\nfrom Contentful. Note that there is no fallback locale for Contentful content other than a redirect to the en-US version\nof the page - either the page is definitely available in a locale, or it’s not at all available in that locale.\nNotes:\n • The batching of jobs in Smartling is still manual, even though the data flow is automated. We need to keep an\n eye on how onerous this is, plus what the cost exposure could be like if we fully automate it.\n • The Smartling integration is currently only set to use Mozilla.org’s 10 most popular locales, in addition to en-US.\n • No localisation of Contentful content happens via Pontoon.\n • The Smartling setup is most effectively leveraged with Compose-based pages rather than Connect-based com-\n ponents, and the latter may require some code tweaks.\n • Our Compose: SEO field in Contentful is configured for translation (and in use on the VPN Resource Center).\n All Compose pages require this field. If a Compose page type is not meant to be localised, we need to stop these\n SEO-related fields from going on to Smartling.\nFluent\nNB: Not selected for use, but notes retained for reference\nInstead of using the language translation fields in Contentful to store translations we could designate one of the locales\nto contain a fluent string ID. Bedrock could then use the string IDs and the English content to create Fluent files for\nsubmission into our current translation system.\nCreation of the string IDs could be automated using Contentful’s write API.\nTo give us the ability to use fallback strings the Contentful field could accept a comma separated list of values.\nThis approach requires significant integration code on the bedrock side but comes with the benefit of using our current\ntranslation system, including community contributions.\nNo English Equivalent\nNB: Not selected for use, but notes retained for reference\nComponents could be created in the language they are intended to display in. The localized content would be written\nin the English content fields.\nThe down sides of this are that we do not know what language the components are written in and could accidentally\ndisplay the wrong language on any page. It also means that localized content cannot be created automatically by English\neditors and translations would have to be manually associated with URLs.\nThis is the approach that will likely be used for the German and French homepages since that content is not going to\nbe used on English pages and creating a separate homepage with different components is valuable to the German and\nFrench teams.\n70 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.9.7 Assets\nImages that are uploaded in Contentful will be served to site visitors from the Contentful CDN. The cost of using the\nCDN are not by request so we don’t have to worry about how many times an image will be requested.\nUsing the Contentful CDN lets us use their Images API to format our images.\nIn theory, a large high quality image is uploaded in Contentful and then bedrock inserts links to the CDN for images\nwhich are cropped to fit their component and resized to fit their place on the page.\nBecause we cannot rely on the dimensions of the image uploaded to Contentful as a guide for displaying the image -\nbedrock needs to be opinionated about what size images it requests based on the component and its configuration. For\nexample, hero images are fixed at 800px wide. In the future this could be a user configurable option.\n1.9.8 Preview\nContent previews are configured under Settings > Content preview on a per-content model basis. At the moment\npreviews are only configured for pages, and display on demo5.\nOnce the code is merged into bedrock they should be updated to use the dev server.\nSpecific URLs will only update every 5 minutes as the data is pulled from the API but pages can be previewed up to\nthe second at the contentful-preview URL. This preview will include “changed” and “draft” changes (even if there is\nan error in the data) not just published changes.\nFor previewing on localhost, see Development Practices, below.\n1.9.9 Roles/Permissions\nIn general we are trusting people to check their work before publishing and very few guard rails have been installed.\nWe have a few roles with different permissions.\nAdmin\n Organization\n • Define roles and permission\n • Manage users\n • Change master and sandbox environment aliases\n • Create new environments\n Master environment\n • Edit content model\n • Create, Edit, Publish, Archive, Delete content\n • Install/Uninstall apps\nDeveloper\n Organization\n • Create new environments\n Master environment\n • Create, Edit, Publish, Archive content\n Sandbox environments (any non-master environment)\n • Edit content model\n1.9. Contentful CMS (Content Management System) Integration 71\nbedrock Documentation, Release 1.0\n • Create, Edit, Publish, Archive, Delete content\n • Install/Uninstall apps\nEditor (WIP)\n Master environment (through Compose)\n • Create, Edit, Publish, Archive content\n1.9.10 Development practices\nThis section outlines tasks generally required if developing features against Contentful.\nGet bedrock set up locally to work with Contentful\nIn your .env file for Bedrock, make sure you have the followign environment variables set up.\n • CONTENTFUL_SPACE_ID - this is the ID of our Contentful integration\n • CONTENTFUL_SPACE_KEY - this is the API key that allows you access to our space. Note that two types of key\n are available: a Preview key allows you to load in draft content; the Delivery key only loads published contnet.\n For local dev, you want a Preview key.\n • SWITCH_CONTENTFUL_HOMEPAGE_DE should be set to True if you are working on the German Contentful-\n powered homepage\n • CONTENTFUL_ENVIRONMENT Contentful has ‘branches’ which it calls environments. master is what we use in\n production, and sandbox is generally what we use in development. It’s also possible to reference a specific\n environment - e.g. CONTENTFUL_ENVIRONMENT=sandbox-2021-11-02\nTo get values for these vars, please check with someone on the backend team.\nIf you are working on the Contentful Sync backed by the message-queue (and if you don’t know what this is, you don’t\nneed it for local dev), you will also need to set the following env vars:\n • CONTENTFUL_NOTIFICATION_QUEUE_URL\n • CONTENTFUL_NOTIFICATION_QUEUE_REGION\n • CONTENTFUL_NOTIFICATION_QUEUE_ACCESS_KEY_ID\n • CONTENTFUL_NOTIFICATION_QUEUE_SECRET_ACCESS_KEY\nHow to preview your changes on localhost\nWhen viewing a page in Contentful, it’s possible to trigger a preview of the draft page. This is typically rendered on\nwww-dev.allizom.org. However, that’s only useful for code that’s already in main. If you want to preview Contentful\ncontent on your local machine - e.g. you’re working on a feature branch that isn’t ready for merging - do the following:\n72 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nExisting (master) Content Types\nIn the right-hand sidebar of the editor page in Contentful:\n • Find the Preview section\n • Select Change and pick Localhost Preview\n • Click Open preview\nNew (non-master) Content Types\nIn bedrock:\n • Update class ContentfulPreviewView(L10nTemplateView) in Mozorg Views with a render case for your\n new content type\nIn the right-hand sidebar of the editor page in Contentful:\n • Click Info tab\n • Find Entry ID section and copy the value\nManually create preview URL in browser:\n • http://localhost:8000/en-US/contentful-preview/{entry_id}/\nNote that previewing a page will require it to be pulled from Contentful’s API, so you will need CONTENTFUL_SPACE_ID\nand CONTENTFUL_SPACE_KEY set in your .env. It may take a few seconds to get the data.\nAlso note that when you select Localhost preview, the choice sticks, so you should set it back to Preview on web\nwhen you’re done.\nHow to update/refresh the sandbox environment\nIt helps to think of Contentful ‘environments’ as simply branches of a git-like repo full of content. You can take a par-\nticular environment and branch off it to make a new environment for WIP (Work in Progress) or experimental content,\nusing the original one as your starting point. On top of this, Contentful has the concept of aliases for environments and\nwe use two aliases in our setup:\n • master is used for production and is an alias currently pointing to the V1 environment. It is pretty stable and\n access to it is limited.\n • sandbox is used for development and more team members have access to edit content. Again, it’s an alias and\n is pointed at an environment (think, branch) with a name in the format sandbox-YYYY-MM-DD.\nWhile updating master is something that we generally don’t do (at the moment only a product owner and/or admin\nwould do this), updating the sandbox happens more often, typically to populate it with data more recently added to\nmaster. To do this:\n • Go to Settings > Environments\n • Ensure we have at least one spare environment slot. If we don’t delete the oldest sandbox-XXXX-XX-XX envi-\n ronment.\n • Click the blue Add Environment button, to the right. Name it using the sandbox-YYYY-MM-DD pattern and\n base it on whatever environment is aliased to master - this will basically create a new ‘branch’ with the content\n currently in master.\n • In the Environment Aliases section of the main page, find sandbox and click Change alias target, then select the\n sandbox-XXXX-XX-XX environment you just made.\n1.9. Contentful CMS (Content Management System) Integration 73\nbedrock Documentation, Release 1.0\nWhich environment is connected to where?\nmaster is the environment used in Bedrock production, stage, dev and test sandbox may, in the future, be made the\ndefault environment for dev. It’s also the one we should use for local development.\nIf you develop a new feature that adds to Contentful (e.g. page or component) and you author it in the sandbox, you\nwill need to re-create it in master before the corresponding bedrock changes hit production.\nTroubleshooting\nIf you run into trouble on an issue, be sure to check in these places first and include the relevant information in requests\nfor help (i.e. environment).\nContentful Content Model & Entries\n • What environment are you using?\n • Do you have the necessary permissions to make changes?\n • Do you see all the entry fields you need? Do those fields have the correct value options?\nBedrock API (api.py)\n • What environment are you using?\n • Can you find a Python function definition for the content type you need?\n • Does it structure data as expected?\n# example content type def\ndef get_section_data(self, entry_obj):\n fields = entry_obj.fields()\n # run `print(fields)` here to verify field values from Contentful\n data = {\n \"component\": \"sectionHeading\",\n \"heading\": fields.get(\"heading\"),\n }\n # run `print(data)` here to verify data values from Bedrock API\n return data\nBedrock Render (all.html)\n • Can you find a render condition for the component you need?\n/* example component condition */\n{% elif entry.component == 'sectionHeading' %}\n • If the component calls a macro:\n74 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n – Does it have all the necessary parameters?\n – Is it passing the expected values as arguments?\n • If the component is custom HTML:\n – Is the HTML structure correct?\n – Are Protocol-specific class names spelled correctly?\n • Is the component CSS available?\n • Is the component JS available?\nNote: Component CSS and JS are defined in a CONTENT_TYPE_MAP from the Bedrock API (api.py).\nBedrock Database\nOnce content is synced into your local database, it can be found in the contentful_contentfulentry table. All the depen-\ndencies to explore the data are installed by default for local development.\nUsing sqlite (with an example query to get some info about en-US pages):\n./manage.py dbshell\nselect id, slug, data from contentful_contentfulentry where locale='en-US';\nClose the sqlite shell with .exit\nUsing Django shell (with an example query to get data from first entry of “pageProductJournalismStory” type):\n./manage.py shell\nfrom bedrock.contentful.models import ContentfulEntry\nproduct_stories = ContentfulEntry.objects.filter(content_type=\"pageProductJournalismStory\n ˓→\", localisation_complete=True, locale=\"en-US\")\nproduct_stories[0].data # to see the data stored for the first story in the results\nClose the Djanjo shell with exit() or CTRL+D\n1.9.11 Useful Contentful Docs\nhttps://www.contentful.com/developers/docs/references/images-api/#/reference/resizing-&-cropping/\nspecify-focus-area\nhttps://www.contentful.com/developers/docs/references/content-delivery-api/\nhttps://contentful.github.io/contentful.py/#filtering-options\nhttps://github.com/contentful/rich-text-renderer.py https://github.com/contentful/rich-text-renderer.py/blob/\na1274a11e65f3f728c278de5d2bac89213b7470e/rich_text_renderer/block_renderers.py\n1.9. Contentful CMS (Content Management System) Integration 75\nbedrock Documentation, Release 1.0\n1.9.12 Assumptions we still need to deal with\n • image sizes\n1.9.13 Legacy\nSince we decided to move forward the the Compose App, we no longer need the Connect content model. The EN-US\nhomepage is currently still using Connect. Documentation is here for reference.\n • this component is referenced by ID in bedrock (at the moment that is just the homepage but could be used to\n connect single components for display on non-contentful pages. For example: the latest feature box on /new)\nConnect\nThese are the highest level component. They should be just a name and entry reference.\nThe purpose of the connect is to create a stable ID that can be referenced in bedrock to be included in a jinja template.\nRight now we only do this for the homepage. This is because the homepage has some conditional content above and\nbelow the Contentful content.\nUsing a connect component to create the link between jinja template and the Contentful Page entry means an entire\nnew page can be created and proofed in Contentful before the bedrock homepage begins pulling that content in.\nIn other contexts a connect content model could be created to link to entries where the ID may change. For example: the\n“Latest Firefox Features: section of /new could be moved to Contentful using a connect component which references\n3 picto blocks.\nBecause the ID must be added to a bedrock by a dev, only devs should be able to make new connect entries.\n1.10 Sitemaps\nbedrock serves a root sitemap at /sitemap.xml, which links to localised sitemaps for each supported locale.\nThe sitemap data is (re)generated on a schedule by www-sitemap-generator and then is pulled into bedrock’s database,\nfrom which the XML sitemaps are rendered.\n1.10.1 Quick summary\nWhat does www-sitemap-generator do?\nwww-sitemap-generator, ultimately, produces an updated sitemap.json file if it detects changes in pages since\nthe last time the sitemap was generated. It does this by loading every page and checking its ETag. This sitemap.json\ndata is key to sitemap rendering by bedrock.\nThe update process is run on a schedule via our Gitlab CI setup.\nNote: www-sitemap-generator uses the main bedrock release Docker image as its own base container image,\nwhich means it has access to all of bedrock’s code and data-loading utils.\nBear this in mind when looking at management commands in bedrock; update_sitemaps is actually only called by\nwww-sitemap-generator even though it (currently) lives in bedrock\n76 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nWhen is the sitemap data pulled into bedrock?\nBedrock’s clock pod regularly runs bin/run-db-update.sh, which calls the update_sitemaps_data management\ncommand. This is what pulls in data from the www-sitemap-generator git repo and refreshes the SitemapURL\nrecords in Bedrock’s database. It is from these SitemapURL records that the XML sitemap tree is rendered by bedrock.\n1.11 Using External Content Cards Data\nThe www-admin repo contains data files and images that are synced to bedrock and available for use on any page. The\ndocs for updating said data is available via that repo, but this page will explain how to use the cards data once it’s in\nthe bedrock database.\n1.11.1 Add to a View\nThe easiest way to make the data available to a page is to add the page_content_cards variable to the template\ncontext:\nfrom bedrock.contentcards.models import get_page_content_cards\ndef view_with_cards(request):\n locale = l10n_utils.get_locale(request)\n ctx = {'page_content_cards': get_page_content_cards('home', locale)}\n return l10n_utils.render(request, 'sweet-words.html', ctx)\nThe get_page_content_cards returns a dict of card data dicts for the given page (home in this case) and locale. The\ndict keys are the names of the cards (e.g. card_1). If the page_content_cards context variable is available in the\ntemplate, then the content_card() macro will discover it automatically.\nNote: The get_page_content_cards function is not all that clever as far as l10n is concerned. If you have translated\nthe cards in the www-admin repo that is great, but you should have cards for every locale for which the page is active\nor the function will return an empty dict. This is especially tricky if you have multiple English locales enabled (en-\nUS, en-CA, en-GB, etc.) and want the same cards to be used for all of them. You’d need to do something like if\nlocale.startswith('en-'): then use en-US in the function call.\nAlternately you could just wrap the section of the template using cards to be optional in an {% if\npage_content_cards %} statement, and that way it will not show the section at all if the dict is empty if there\nare no cards for that page and locale combination.\n1.11.2 Add to the Template\nOnce you have the data in the template context, using a card is simple:\n{% from \"macros-protocol.html\" import content_card with context %}\n{{ content_card('card_1') }}\nThis will insert the data from the card_1.en-US.md file from the www-admin repo into the template via the card()\nmacro normally used for protocol content cards.\nIf you don’t have the page_content_cards variable in the template context and you don’t want to create or modify a\nview, you can fetch the cards via a helper function in the template itself, but you have to pass the result to the macro:\n1.11. Using External Content Cards Data 77\nbedrock Documentation, Release 1.0\n{% from \"macros-protocol.html\" import content_card with context %}\n{% set content_cards = get_page_content_cards('home', LANG) %}\n{{ content_card('card_1', content_cards) }}\n1.12 Banners\n1.12.1 Creating page banners\nAny page on bedrock can incorporate a top of page banner as a temporary feature. An example of such a banner is the\nMOFO (Mozilla Foundation) fundraising form that gets shown on the home page several times a year.\nBanners can be inserted into any page template by using the page_banner block. Banners can also be toggled on and\noff using a switch:\n{% block page_banner %}\n {% if switch('fundraising-banner') %}\n {% include 'includes/banners/fundraiser.html' %}\n {% endif %}\n{% endblock %}\nBanner templates should extend the base banner template, and content can then be inserted using banner_title and\nbanner_content blocks:\n{% extends 'includes/banners/base.html' %}\n{% block banner_title %}We all love the web. Join Mozilla in defending it.{% endblock %}\n{% block banner_content %}\n \n{% endblock %}\nCSS styles for banners should be located in media/css/base/banners/, and should extend common base banner\nstyles:\n@import 'includes/base';\nTo initiate a banner on a page, include js/base/banners/mozilla-banner.js in your page bundle and then initiate\nthe banner using a unique ID. The ID will be used as a cookie identifier should someone dismiss a banner and not wish\nto see it again.\n(function() {\n 'use strict';\n function onLoad() {\n window.Mozilla.Banner.init('fundraising-banner');\n }\n window.Mozilla.run(onLoad);\n})();\n78 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nBy default, page banners will be rendered directly underneath the primary page navigation. If you want to render a\nbanner flush at the top of the page, you can pass a secondary renderAtTopOfPage parameter to the init() function\nwith a boolean value:\n(function() {\n 'use strict';\n function onLoad() {\n window.Mozilla.Banner.init('fundraising-banner', true);\n }\n window.Mozilla.run(onLoad);\n})();\nL10n for page banners\nBecause banners can technically be shown on any page, they need to be broadly translated, or alternatively limited to\nthe subset of locales that have translations. Each banner should have its own .ftl associated with it, and accessible to\nthe template or view it gets used in.\n1.13 Mozilla.UITour\n1.13.1 Introduction\nMozilla.UITour is a JS library that exposes an event-based Web API for communicating with the Firefox browser\nchrome. It can be used for tasks such as opening menu panels, highlighting buttons, or querying Firefox Account\nsigned-in state. It is supported in Firefox 29 onward, but some API calls are only supported in later versions.\nFor security reasons Mozilla.UITour will only work on white-listed domains and over a secure connection. The list\nof allowed origins can be found here: https://searchfox.org/mozilla-central/source/browser/app/permissions\nThe Mozilla.UITour library is maintained on Mozilla Central.\nImportant: The API is supported only on the desktop versions of Firefox. It doesn’t work on Firefox for Android and\niOS.\n1.13.2 Local development\nTo develop or test using Mozilla.UITour locally you need to create some custom preferences in about:config.\n • browser.uitour.testingOrigins (string) (value: local address e.g. http://127.0.0.1:8000)\n • browser.uitour.requireSecure (boolean) (value: false)\nNote that browser.uitour.testingOrigins can be a comma separated list of domains, e.g.\n ‘http://127.0.0.1:8000, https://www-demo2.allizom.org’\n1.13. Mozilla.UITour 79\nbedrock Documentation, Release 1.0\nImportant: Prior to Firefox 36, the testing preference was called browser.uitour.whitelist.add.testing\n(Bug 1081772). This old preference does not accept a comma separated list of domains, and you must also exclude the\ndomain protocol e.g. https://. A browser restart is also required after adding an allowed domain.\nIf you are working on Firefox Accounts integration, you can use the identity.fxaccounts.autoconfig.uri config\nproperty to change the Accounts server. For example, to change it to stage environment use this value: https:/\n/accounts.stage.mozaws.net/. Restart the browser and make sure the configuration updated. identity.\nfxaccounts.remote.root preference should now point to https://accounts.stage.mozaws.net. If it has not\nchanged for some reason, update it manually. Ref: https://mozilla-services.readthedocs.io/en/latest/howtos/run-fxa.\nhtml\n1.13.3 JavaScript API\nThe UITour API documentation can be found in the Mozilla Source Tree Docs.\n1.14 Send to Device Widget\nThe Send to Device widget is a single form which facilitates the sending of a download link from a desktop browser to\na mobile device. The form allows sending via email.\nImportant: This widget should only be shown to a limited set of locales who are set up to receive the emails. For those\nlocales not in the list, direct links to the respective app stores should be shown instead. If a user is on iOS or Android,\nCTA buttons should also link directly to respective app stores instead of showing the widget. This logic should be\nhandled on a page-by-page basis to cover individual needs.\nNote: A full list of supported locales can be found in settings/base.py under SEND_TO_DEVICE_LOCALES, which\ncan be used in the template logic for each page to show the form.\n1.14.1 Usage\n 1. Make sure necessary files are in your CSS/JS bundles:\n • 'css/protocol/components/send-to-device.scss'\n • 'js/base/send-to-device.es6.js'\n 2. Include the macro in your page template:\n {{ send_to_device() }}\n 3. Initialize the widget:\n In your page JS, initialize the widget using:\n import SendToDevice from '/media/js/base/send-to-device.es6';\n const form = new SendToDevice();\n form.init();\n80 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n By default the init() function will look for a form with an HTML id of send-to-device. If you need\n to pass another id, you can do so directly:\n const form = new SendToDevice('my-custom-form-id');\n form.init();\nConfiguration\nThe Jinja macro supports parameters as follows (* indicates a required parameter)\n Parame- Definition Format Example\n ter name\n platform* Platform ID for the receiving device. De- String ‘all’, ‘android’, ‘ios’\n faults to ‘all’.\n mes- ID for the email that should be received. String ‘default’, ‘fx-mobile-download-desktop’,\n sage_set* Defaults to ‘default’. ‘download-firefox-rocket’\n dom_id* HTML form ID. Defaults to ‘send-to- String ‘send-to-device’\n device’.\n class_name CSS class name for form orientation. String ‘horizontal’, ‘vertical’\n Defaults to ‘vertical’\n in- Should the widget contain a title. De- Boolean ‘True’, ‘False’\n clude_title faults to ‘True’.\n title_text Provides a custom string for the form ti- Localizable ‘Send Firefox Lite to your smartphone or\n tle, overriding the default. string tablet’ .\n input_label Provides a custom label for the input Localizable ‘Enter your email’ .\n field, overriding the default. string\n le- Provides a custom legal note for email Localizable ‘The intended recipient of the email must\n gal_note_emailuse. String. have consented.’\n spin- Hex color for the form spinner. Defaults String ‘#fff’\n ner_color to ‘#000’.\n but- Optional button CSS class string. De- String ‘mzp-t-product mzp-t-dark’\n ton_class faults to ‘mzp-t-product’\n1.15 Firefox Download Buttons\nThere are two Firefox download button helpers in bedrock to choose from. The first is a lightweight button that links\ndirectly to the /firefox/download/thanks/ page. Its sole purpose is to facilitate downloading the main release\nversion of Firefox.\n{{ download_firefox_thanks() }}\nThe second type of button is more heavy weight, and can be configured to download any build of Firefox (e.g. Release,\nBeta, Developer Edition, Nightly). It can also offer functionality such as direct (in-page) download links, so it comes\nwith a lot more complexity and in-page markup.\n{{ download_firefox() }}\n1.15. Firefox Download Buttons 81\nbedrock Documentation, Release 1.0\n1.15.1 Which button should I use?\nA good rule of thumb is to always use download_firefox_thanks() for regular landing pages (such as /firefox/\nnew/) where the main release version of Firefox is the product being offered. For pages pages that require direct\ndownload links, or promote pre-release products (such as /firefox/channel/) then download_firefox() should\nbe used instead.\n1.15.2 Documentation\nSee helpers.py for documentation and supported parameters for both buttons.\n1.15.3 External referrers\nGenerally we encourage other websites in the Mozilla ecosystem to link to the /firefox/new/ page when prompting\nvisitors to download Firefox, since it provides a consistent user experience and also benefits SEO (Search Engine Op-\ntimization). In some circumstances however sites may want to provide a download button that initiates a file download\nautomatically when clicked. For cases like this, sites can link to the following URL:\nhttps://www.mozilla.org/firefox/download/thanks/?s=direct\nImportant: Including the s=direct query parameter here will ensure that Windows download attribution is collected\nand recorded correctly in Telemetry. Also, make sure to not include the locale in the URL, so that bedrock can serve\nthe most suitable language based on the visitor’s browser preference.\nNote: This download URL will not automatically trigger a download in older Internet Explorer browsers. If that’s\nimportant to your visitors, then you can use a conditional comment to provide a different link.\n\n Download Firefox\n ˓→\n\n\n1.16 Firefox Accounts Helpers\nMarketing pages often promote the creation of a Firefox Account (FxA) as a common call to action (CTA). This is\ntypically accomplished using either a sign-up form, or a prominent link/button. Other products such as Mozilla VPN\nuse similar Firefox Account auth flows to manage subscriptions. To accomplish these tasks, bedrock templates can take\nadvantage of a series of Python helpers which can be used to standardize product referrals, and make supporting these\nauth flows easier.\nNote: See the attribution docs (Firefox Accounts attribution) for more a detailed description of the analytics functions\nthese helpers provide.\n82 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.16.1 Firefox Account Sign-up Form\nUse the fxa_email_form macro to display a Firefox Account signup form on a page.\nUsage\nTo use the form in a Jinja template, first import the fxa_email_form macro:\n{% from \"macros.html\" import fxa_email_form with context %}\nThe form can then be invoked using:\n{{ fxa_email_form(entrypoint='mozilla.org-firefox-accounts') }}\nThe macro’s respective JavaScript and CSS dependencies should also be imported in the page:\nJavascript:\nimport FxaForm from './path/to/fxa-form.es6.js';\nFxaForm.init();\nThe above JS is also available as a pre-compiled bundle, which can be included directly in a template:\n{{ js_bundle('fxa_form') }}\nCSS:\n@import '../path/to/fxa-form';\nThe JavaScript files will automatically handle things such as adding metrics parameters for Firefox desktop browsers.\nThe CSS file contains some default styling for the sign-up form.\n1.16. Firefox Accounts Helpers 83\nbedrock Documentation, Release 1.0\nConfiguration\nThe sign-up form macro accepts the following parameters (* indicates a required parameter)\n Param- Definition Format Example\n eter\n name\n entry- Unambiguous identifier for which page of the site is mozilla.org-directory- ‘mozilla.org-\n point* the referrer. page firefox-accounts’\n entry- Used to identify experiments. Experiment ID ‘whatsnew-\n point_experiment headlines’\n entry- Used to track page variations in multivariate tests. Variant identifier ‘b’\n point_variation\n Usually just a number or letter but could be a short\n keyword.\n style An optional parameter used to invoke an alternatively String ‘trailhead’\n styled page at accounts.firefox.com.\n class_name Applies a CSS class name to the form. Defaults to: String ‘fxa-email-form’\n ‘fxa-email-form’\n form_title The main heading to be used in the form (optional Localizable string ‘Join Firefox’ .\n with no default).\n intro_text Introductory copy to be used in the form. Defaults to Localizable string ‘Enter your email\n a well localized string. address to get\n started.’ .\n but- Button copy to be used in the form. Defaults to a well Localizable string ‘Sign Up’ .\n ton_text localized string.\n but- CSS class names to be applied to the submit button. String of one or more ‘mzp-c-button\n ton_class CSS class names mzp-t-primary\n mzp-t-product’\n utm_campaign Used to identify specific marketing campaigns. De- Campaign name ‘trailhead-fxa-\n faults to fxa-embedded-form prepended to default embedded-form’\n value\n utm_term Used for paid search keywords. Brief keyword ‘existing-users’\n utm_contentDeclared when more than one piece of content (on a Description of content, ‘get-the-rest-of-\n page or at a URL) links to the same place, to distin- or name of experiment firefox’\n guish between them. treatment\nInvoking the macro will automatically include a set of default UTM (Urchin Tracking Module) parameters as hidden\nform input fields:\n • utm_source is automatically assigned the value of the entrypoint parameter.\n • utm_campaign is automatically set as the value of fxa-embedded-form. This can be prefixed with a custom\n value by passing a utm_campaign value to the macro. For example, utm_campaign='trailhead' would result\n in a value of trailhead-fxa-embedded-form.\n • utm_medium is automatically set as the value of referral.\nNote: When signing into FxA using this form on a Firefox Desktop browser, it will also activate the Sync feature.\n84 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.16.2 Firefox Account Links\nUse the fxa_button helper to create a CTA button or link to https://accounts.firefox.com/.\nUsage\n{{ fxa_button(entrypoint='mozilla.org-firefox-accounts', button_text='Sign In') }}\nNote: There is also a fxa_link_fragment helper which will construct a valid href property. This is useful when\nconstructing an inline link inside a paragraph, for example.\nNote: When signing into FxA using this link on a Firefox Desktop browser, it will also activate the Sync feature.\nFor more information on the available parameters, read the “Common FxA Parameters” section further below.\n1.16.3 Firefox Monitor Links\nUse the monitor_fxa_button helper to link to https://monitor.firefox.com/ via a Firefox Accounts auth flow.\nUsage\n{{ monitor_fxa_button(entrypoint=_entrypoint, button_text='Sign Up for Monitor') }}\nFor more information on the available parameters, read the “Common FxA Parameters” section further below.\n1.16.4 Pocket Links\nUse the pocket_fxa_button helper to link to https://getpocket.com/ via a Firefox Accounts auth flow.\nUsage\n{{ pocket_fxa_button(entrypoint='mozilla.org-firefox-pocket', button_text='Try Pocket Now\n ˓→', optional_parameters={'s': 'ffpocket'}) }}\nFor more information on the available parameters, read the “Common FxA Parameters” section below.\n1.16.5 Common FxA (Firefox Account) Parameters\nThe fxa_button, pocket_fxa_button, and monitor_fxa_button helpers all support the same standard parame-\nters:\n1.16. Firefox Accounts Helpers 85\nbedrock Documentation, Release 1.0\n Param- Definition Format Example\n eter\n name\n entry- Unambiguous identifier for which page of ‘mozilla.org- ‘mozilla.org-firefox-pocket’\n point* the site is the referrer. This also serves as firefox-\n a value for ‘utm_source’. pocket’\n but- The button copy to be used in the call to ac- Localizable ‘Try Pocket Now’\n ton_text* tion. string\n class_nameA class name to be applied to the link (typi- String of one ‘pocket-main-cta-button’\n cally for styling with CSS). or more class\n names\n is_button_class\n A boolean value that dictates if the CTA Boolean True or False\n should be styled as a button or a link. De-\n faults to ‘True’.\n in- A boolean value that dictates if metrics pa- Boolean True or False\n clude_metrics\n rameters should be added to the button href.\n Defaults to ‘True’.\n op- An dictionary of key value pairs containing Dictionary {‘s’: ‘ffpocket’}\n tional_parameters\n additional parameters to append the the href.\n op- An dictionary of key value pairs containing Dictionary {‘data-cta-text’: ‘Try Pocket Now’,\n tional_attributes\n additional data attributes to include in the ‘data-cta-type’: ‘activate pocket’,’data-\n button. cta-position’: ‘primary’}\nNote: The fxa_button helper also supports an additional action parameter, which accepts the values signup,\nsignin, and email for configuring the type of authentication flow.\n1.16.6 Mozilla VPN (Virtual Private Network) Links\nUse the vpn_subscribe_link helpers to create a VPN subscription link via a Firefox Accounts auth flow.\nUsage\n{{ vpn_subscribe_link(entrypoint='www.mozilla.org-vpn-product-page', link_text='Get␣\n ˓→Mozilla VPN') }}\nCommon VPN Parameters\nBoth helpers for Mozilla VPN support the same parameters (* indicates a required parameter)\n86 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n Param- Definition Format Example\n eter\n name\n entry- Unambiguous identifier for which page of the ‘www.mozilla.org-‘www.mozilla.org-vpn-product-page’\n point* site is the referrer. This also serves as a value page-name’\n for ‘utm_source’.\n link_text* The link copy to be used in the call to action. Localizable ‘Get Mozilla VPN’\n string\n class_nameA class name to be applied to the link (typi- String of one ‘vpn-button’\n cally for styling with CSS). or more class\n names\n lang Page locale code. Used to query the right sub- Locale string ‘de’\n scription plan ID in conjunction to country\n code.\n coun- Country code provided by the CDN. Used to Two digit, up- ‘DE’\n try_code determine the appropriate subscription plan percase coun-\n ID. try code\n bun- Generate a link that will bundle both Mozilla Boolean True, False\n dle_relay VPN and Firefox Relay in a single subscrip-\n tion. Defaults to False.\n op- An dictionary of key value pairs containing Dictionary {‘utm_campaign’: ‘vpn-product-\n tional_parameters\n additional parameters to append the the href. page’}\n op- An dictionary of key value pairs containing Dictionary {‘data-cta-text’: ‘VPN Sign In’,\n tional_attributes\n additional data attributes to include in the but- ‘data-cta-type’: ‘fxa-vpn’, ‘data-cta-\n ton. position’: ‘navigation’}\nThe vpn_subscribe_link helper has an additional plan parameter to support linking to different subscription plans.\n Parameter name Definition Format Example\n plan Subscription plan ID. Defaults to 12-month plan. ‘12-month’ ‘12-month’ or ‘monthly’\n1.16.7 Firefox Sync and UITour\nSince Firefox 80 the FxA link and email form macros use UITour to show the Firefox Accounts page and log the\nbrowser into Sync or an Account. For non-Firefox browsers or if UITour is not available, the flow uses normal links\nthat allow users to log into FxA as a website only without connecting the Firefox Desktop client. This UITour flow\nallows the Firefox browser to determine the correct FxA server and authentication flow (this includes handling the\nChina Repack build of Firefox). This transition was introduced to later migrate Firefox Desktop to an OAuth based\nclient authentication flow.\nThe script that handles this logic is /media/js/base/fxa-link.js, and will automatically apply to any link with\na js-fxa-cta-link class name. The current code automatically detects if you are in the supported browser for this\nflow and updates links to drive them through the UITour API. The UITour showFirefoxAccounts action supports\nflow id parameters, UTM parameters and the email data field.\n1.16. Firefox Accounts Helpers 87\nbedrock Documentation, Release 1.0\n1.16.8 Testing Signup Flows\nTesting the Firefox Account signup flows on a non-production environment requires some additional configuration.\nConfiguring bedrock:\nSet the following in your local .env file:\nFXA_ENDPOINT=https://accounts.stage.mozaws.net/\nFor Mozilla VPN links you can also set:\nVPN_ENDPOINT=https://stage.guardian.nonprod.cloudops.mozgcp.net/\nVPN_SUBSCRIPTION_URL=https://accounts.stage.mozaws.net/\nNote: The above values for staging are already set by default when Dev=True, which will also apply to demo servers.\nYou may only need to configure your .env file if you wish to change a setting to something else.\n1.17 Funnel cakes and Partner Builds\n1.17.1 Funnel cakes\nIn addition to being an American delicacy funnel cakes are what we call special builds of Firefox. They can come with\nextensions preinstalled and/or a custom first-run experience.\n “The whole funnelcake system is so marred by history at this point I don’t know if anyone fully understands\n what it’s supposed to do in all situations” - pmac\nFunnelcakes are configured by the Release Engineering team. You can see the configs in the funnelcake git repo\nCurrently bedrock only supports funnelcakes for “stub installer platforms”. Which means they are windows only.\nHowever, funnelcakes can be made for all platforms so bedrock support may expand.\nWe signal to bedrock that we want a funnelcake when linking to the download page by appending the query variable f\nwith a value equal to the funnelcake number being requested.\nhttps://www.mozilla.org/en-US/firefox/download/thanks/?f=137\nBedrock checks to see if the funnelcake is configured (this is handled in the www-config repo)\nFUNNELCAKE_135_LOCALES=en-US\nFUNNELCAKE_135_PLATFORMS=win,win64\nBedrock then converts that into a request to download a file like so:\nWindows:\nhttps://download.mozilla.org/?product=firefox-stub-f137&os=win&lang=en-US\nMac (You can see the mac one does not pass the funnelcake number along.):\nhttps://download.mozilla.org/?product=firefox-latest-ssl&os=osx&lang=en-US\nSomeone in Release Engineering needs to set up the redirects on their side to take the request from here.\n88 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nPlaces things can go wrong\nAs with many technical things, the biggest potential problems are with people:\n • Does it have executive approval?\n • Did legal sign off?\n • Has it had a security review?\nOn the technical side:\n • Is the switch enabled?\n • Is the variable being passed?\n1.17.2 Partner builds\nBedrock does not have an automated way of handling these, so you’ll have to craft your own download button:\n\nDownload\nBugs that might have useful info:\n • https://bugzilla.mozilla.org/show_bug.cgi?id=1450463\n • https://bugzilla.mozilla.org/show_bug.cgi?id=1495050\nPRs that might have useful code:\n • https://github.com/mozilla/bedrock/pull/5555\n1.18 A/B Testing\n1.18.1 Convert experiments\nConversion rate optimization (CRO) experiments on bedrock can be run using a third-party tool called Convert. Convert\nexperiments are for relatively simple multivariate experiments, such as testing changes to headlines, images, or button\ncopy.\nThe Convert script is not included in part of bedrock’s base bundle for performance reasons. To use Convert on a page,\nyou can load the script behind a feature flag, which can be turned on / off for only the duration of an experiment. The\nscript should be loaded inside the experiments block in your template:\n{% block experiments %}\n {% if switch('experiment-convert-page-name', ['en-US']) %}\n {{ js_bundle('convert') }}\n {% endif %}\n{% endblock %}\nConvert A/B tests can be implemented using the Convert dashboard and editor. Convert experiments should be coded\nand tested against staging, before being reviewed and scheduled to run in production.\n1.18. A/B Testing 89\nbedrock Documentation, Release 1.0\nQA for Convert experiments\nThe process for QA’ing Convert experiments is as follows:\n 1. Bedrock feature switch should be activated on staging.\n 2. Experiment is built and configured to run on https://www.allizom.org/*\n 3. In the Github issue for an experiment, someone will request review by an engineer.\nAn engineer reviewing the experiment will:\n 1. Verify that the experiment is not configured to run on https://www.mozilla.org/ (production) yet.\n 2. Activate the experiment to run on stage.\nDuring review, the engineer will compare the following to the experiment plan:\n 1. The experiment’s logic.\n 2. Any JS included (in Convert editor’s JS field).\n 3. Any CSS included (in Convert editor’s CSS field).\n 4. The target audience is configured.\n 5. The goals are configured.\n 6. The distribution percentages are configured.\n 7. The target URLs are configured.\nOnce the engineer is satisfied, the engineer (or someone else with write privileges) will:\n 1. Add https://www.mozilla.org/* to the list of URLs the experiment can run on.\n 2. Reset the experiment (eliminating any data gathered during QA).\n 3. Enable the bedrock feature switch in production.\n 4. Activate (or schedule) the experiment.\nAfter an experiment is finished, the feature switch should be deactivated in production.\nNote: * should be replaced by the exact URL pathname for the experiment page.\n1.18.2 Traffic Cop experiments\nMore complex experiments, such as those that feature full page redesigns, or multi-page user flows, should be imple-\nmented using Traffic Cop. Traffic Cop small javascript library which will direct site traffic to different variants in a/b\nexperiments and make sure a visitor always sees the same variation.\nIt’s possible to test more than 2 variants.\nTraffic Cop sends users to experiments and then we use Google Analytics (GA) to analyze which variation is more\nsuccessful. (If the user has DNT (Do Not Track) enabled they do not participate in experiments.)\nAll a/b tests should have a mana page detailing the experiment and recording the results.\n90 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nCoding the variants\nTraffic cop supports two methods of a/b testing. Executing different on page javascript or redirecting to the same URL\nwith a query string appended. We mostly use the redirect method in bedrock. This makes testing easier.\nCreate a variation view for the a/b test.\nThe view can handle the URL redirect in one of two ways:\n 1. the same page, with some different content based on the variation variable\n 2. a totally different page\nContent variation\nUseful for small focused tests.\nThis is explained on the variation view page.\nNew page\nUseful for large page changes where content and assets are dramatically different.\nCreate the variant page like you would a new page. Make sure it is noindex and does not have a canonical URL.\n{% block canonical_urls %}{% endblock %}\nConfigure as explained on the variation view page.\nTraffic Cop\nCreate a .js file where you initialize Traffic Cop and include that in the experiments block in the template that will be\ndoing the redirection. Wrap the extra js include in a switch.\n{% block experiments %}\n {% if switch('experiment-berlin-video', ['de']) %}\n {{ js_bundle('firefox_new_berlin_experiment') }}\n {% endif %}\n{% endblock %}\nSwitches\nSee the traffic cop section of the switch docs for instructions.\n1.18. A/B Testing 91\nbedrock Documentation, Release 1.0\nRecording the data\nNote: If you are measuring installs as part of your experiment be sure to configure custom stub attribution as well.\nIncluding the data-ex-variant and data-ex-name in the analytics reporting will add the test to an auto generated\nreport in GA (Google Analytics). The variable values may be provided by the analytics team.\nif (href.indexOf('v=a') !== -1) {\n window.dataLayer.push({\n 'data-ex-variant': 'de-page',\n 'data-ex-name': 'Berlin-Campaign-Landing-Page'\n });\n} else if (href.indexOf('v=b') !== -1) {\n window.dataLayer.push({\n 'data-ex-variant': 'campaign-page',\n 'data-ex-name': 'Berlin-Campaign-Landing-Page'\n });\n}\nMake sure any buttons and interaction which are being compared as part of the test and will report into GA.\nViewing the data\nThe data-ex-name and data-ex-variant are encoded in Google Analytics as custom dimensions 69 and 70.\nCreate a custom report.\nSet the “Metrics Group” to include Sessions. Configure additional metrics depending on what the experiment was\nmeasuring (downloads, events, etc.)\nSet the “Dimension Drilldowns to have cd69 in the top position and cd70 in the drilldown position.\nView the custom report and drilldown into the experiment with the matching name.\nTests\nWrite some tests for your a/b test. This could be simple or complex depending on the experiment.\nSome things to consider checking:\n • Requests for the default (non variant) page call the correct template.\n • Requests for a variant page call the correct template.\n • Locales excluded from the test call the correct (default) template.\n92 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nA/B Test PRs that might have useful code to reuse\n • https://github.com/mozilla/bedrock/pull/5736/files\n • https://github.com/mozilla/bedrock/pull/4645/files\n • https://github.com/mozilla/bedrock/pull/5925/files\n • https://github.com/mozilla/bedrock/pull/5443/files\n • https://github.com/mozilla/bedrock/pull/5492/files\n • https://github.com/mozilla/bedrock/pull/5499/files\n1.18.3 Avoiding experiment collisions\nTo ensure that Traffic Cop doesn’t overwrite data from any other externally controlled experiments (for example Ad\ncampaign tests, or in-product Firefox experiments), you can use the experiment-utils helper to decide whether or not\nTraffic Cop should initiate.\nimport TrafficCop = from '@mozmeao/trafficcop';\nimport { isApprovedToRun } from '../../base/experiment-utils.es6';\nif (isApprovedToRun()) {\n const cop = new TrafficCop({\n id: 'experiment-name',\n variations: {\n 'entrypoint_experiment=experiment-name&entrypoint_variation=a': 10,\n 'entrypoint_experiment=experiment-name&entrypoint_variation=b': 10\n }\n });\n cop.init();\n}\nThe isApprovedToRun() function will check the page URL’s query parameters against a list of well-known experi-\nmental params, and return false if any of those params are found. It will also check for some other cases where we\ndo not want to run experiments, such as if the page is being opened in an automated testing environment.\n1.19 Mozilla VPN Subscriptions\nThe Mozilla VPN landing page displays both pricing and currency information that is dependant on someone’s physical\nlocation in the world (using geo-location). If someone is in the United States, they should see pricing in $USD, and\nif someone is in Germany they should see pricing in Euros. The page is also available in multiple languages, which\ncan be viewed independently of someone’s physical location. So someone who lives in Switzerland, but is viewing the\npage in German, should still see pricing and currency displayed in Swiss Francs (CHF).\nAdditionally, it is important that we render location specific subscription links, as purchasing requires a credit card that\nis registered to each country where we have a plan available. We are also legally obligated to prevent both purchasing\nand/or downloading of Mozilla VPN in certain countries. In countries where VPN is not yet available, we also rely on\ngeo-location to hide subscription links, and instead to display a call to action to encourage prospective customers to\nsign up to the VPN wait list.\n1.19. Mozilla VPN Subscriptions 93\nbedrock Documentation, Release 1.0\nTo facilitate all of the above, we rely on our CDN to return an appropriate country code that relates to where a visitor’s\nrequest originated from (see Geo Template View). We use that country code in our helpers and view logic for the VPN\nlanding page to decide what to display in the pricing section of the page (see Mozilla VPN Links).\n1.19.1 Server architecture\nBedrock is configured so that when dev=True, VPN subscription links will point to the Firefox Accounts (FxA) staging\nenvironment. When dev=False, they will point to the Fxa production environment.\nSo our different environments are mapped like so:\n • http://localhost:8000 -> https://accounts.stage.mozaws.net/\n • https://www-dev.allizom.org/products/vpn/ -> https://accounts.stage.mozaws.net/\n • https://www.allizom.or/products/vpn/ -> https://accounts.firefox.com/\n • https://www.mozilla.org/products/vpn -> https://accounts.firefox.com/\nThis allows the product and QA teams to routinely test changes and new VPN client releases on https://www-dev.\nallizom.org/products/vpn/, prior to being available in production.\n1.19.2 Adding new countries for VPN\nWhen launching VPN in new countries there is a set process to follow.\nLaunch steps\n 1. All the code changes below should be added behind a feature switch.\n 2. Once the PR is reviewed and merged, the product QA team should be notified and they can then perform testing\n on https://www-dev.allizom.org/products/vpn/. Often the QA team will request a date for code to be ready for\n testing to begin.\n 3. Code can be pushed to production ahead of time (but will be disabled behind the feature switch by default).\n 4. Once QA gives the green light on launch day, the feature switch can then be enabled in production.\n 5. QA will then do a final round of post-launch QA to verify subscriptions / purchasing works in the new countries\n in production.\nCode changes\nReference: officially assigned list of ISO country codes. Reference: list of ISO 4217 currency codes`_\nThe majority of config changes need to happen in bedrock/settings/base.py:\n 1. Add new pricing plan configs to VPN_PLAN_ID_MATRIX for any new countries that require newly created plan\n IDs (these will be provided by the VPN team). Separate plan IDs for both dev and prod are required for each\n new currency / language combination (this is because the product QA team need differently configured plans on\n dev to routinely test things like renewal and cancellation flows). Meta data such as price, total price and saving\n for each plan / currency should also be provided.\n Example pricing plan config for $USD / English containing both 12-month and monthly plans:\n94 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n VPN_PLAN_ID_MATRIX = {\n \"usd\": {\n \"en\": {\n \"12-month\": {\n \"id\": \"price_1J0Y1iKb9q6OnNsLXwdOFgDr\" if DEV else \"price_\n ˓→1Iw85dJNcmPzuWtRyhMDdtM7\",\n \"price\": \"US$4.99\",\n \"total\": \"US$59.88\",\n \"saving\": 50,\n \"analytics\": {\"brand\": \"vpn\", \"plan\": \"vpn\", \"currency\":\n ˓→\"USD\", \"discount\": \"60.00\", \"price\": \"59.88\", \"period\": \"yearly\"},\n },\n \"monthly\": {\n \"id\": \"price_1J0owvKb9q6OnNsLExNhEDXm\" if DEV else \"price_\n ˓→1Iw7qSJNcmPzuWtRMUZpOwLm\",\n \"price\": \"US$9.99\",\n \"total\": None,\n \"saving\": None,\n \"analytics\": {\"brand\": \"vpn\", \"plan\": \"vpn\", \"currency\":\n ˓→\"USD\", \"discount\": \"0\", \"price\": \"9.99\", \"period\": \"monthly\"},\n },\n }\n },\n # repeat for other currency / language configs.\n }\n See the Begin Checkout section of the analytics docs for more a detailed description of what should\n be in the analytics objects.\n 2. Map each new country code to one or more applicable pricing plans in VPN_VARIABLE_PRICING.\n Example that maps the US country code to the pricing plan config above:\n VPN_VARIABLE_PRICING = {\n \"US\": {\n \"default\": VPN_PLAN_ID_MATRIX[\"usd\"][\"en\"],\n },\n # repeat for other country codes.\n }\n 3. Once every new country has a mapping to a pricing plan, add each new country code to the list of supported\n countries in VPN_COUNTRY_CODES. Because new countries need to be added behind a feature switch, you may\n want to create a new variable temporarily for this until launched, such as VPN_COUNTRY_CODES_WAVE_VI. You\n can then add these to VPN_COUNTRY_CODES in products/views.py using a simple function like so:\n def vpn_available(request):\n country = get_country_from_request(request)\n country_list = settings.VPN_COUNTRY_CODES\n if switch(\"vpn-wave-vi\"):\n country_list = settings.VPN_COUNTRY_CODES + settings.VPN_COUNTRY_\n ˓→CODES_WAVE_VI\n return country in country_list\n1.19. Mozilla VPN Subscriptions 95\nbedrock Documentation, Release 1.0\n The function could then be used in the landing page view like so:\n vpn_available_in_country = vpn_available(request),\n 4. If you now test the landing page locally, you should hopefully see the newly added pricing for each new country\n (add the ?geo=[INSERT_COUNTRY_CODE] param to the page URL to mock each country). If all is well, this is\n the perfect time to add new unit tests for each new country. This will help give you confidence that the right plan\n ID is displayed for each new country / language option.\n def test_vpn_subscribe_link_variable_12_month_us_en(self):\n \"\"\"Should contain expected 12-month plan ID (US / en-US)\"\"\"\n markup = self._render(\n plan=\"12-month\",\n country_code=\"US\",\n lang=\"en-US\",\n )\n self.assertIn(\"?plan=price_1Iw85dJNcmPzuWtRyhMDdtM7\", markup)\n def test_vpn_subscribe_link_variable_monthly_us_en(self):\n \"\"\"Should contain expected monthly plan ID (US / en-US)\"\"\"\n markup = self._render(\n plan=\"monthly\",\n country_code=\"US\",\n lang=\"en-US\",\n )\n self.assertIn(\"?plan=price_1Iw7qSJNcmPzuWtRMUZpOwLm\", markup)\n 5. Next, update VPN_AVAILABLE_COUNTRIES to the new total number of countries where VPN is available. Again,\n because this needs to be behind a feature switch you may want a new temporary variable that you can use in\n products/views.py:\n available_countries = settings.VPN_AVAILABLE_COUNTRIES\n if switch(\"vpn-wave-vi\"):\n available_countries = settings.VPN_AVAILABLE_COUNTRIES_WAVE_VI\n 6. Finally, there is also a string in l10n/en/products/vpn/shared.ftl that needs updating to include the new\n countries. This should be a new string ID, and behind a feature switch in the template:\n vpn-shared-available-countries-v6 = We currently offer { -brand-name-mozilla-vpn }␣\n ˓→in Austria, Belgium, Canada, Finland, France, Germany, Ireland, Italy, Malaysia,␣\n ˓→the Netherlands, New Zealand, Singapore, Spain, Sweden, Switzerland, the UK, and␣\n ˓→the US.\n {% if switch('vpn_wave_vi') %}\n {{ ftl('vpn-shared-available-countries-v6', fallback='vpn-shared-available-\n ˓→countries-v5') }}\n {% else %}\n {{ ftl('vpn-shared-available-countries-v5') }}\n {% endif %}\n 7. After things are launched in production and QA has verified that all is well, don’t forget to file an issue to tidy\n up the temporary variables and switch logic.\n96 Chapter 1. Contents\n bedrock Documentation, Release 1.0\n1.19.3 Excluded countries\nFor a list of country codes where we are legally obligated to prevent purchasing VPN, see\nVPN_EXCLUDED_COUNTRY_CODES in bedrock/settings/base.py.\nFor a list of country codes where we are also required to prevent downloading the VPN client, see\nVPN_BLOCK_DOWNLOAD_COUNTRY_CODES.\n1.20 Attribution\nAttribution is the practice of recording the main touch points that a website visitor encounters on their path to down-\nloading or signing up for one of our products. It often involves a multi-step user journey, sometimes across multiple\nproperties, but the goal is to end up with informative data that tells us where the user of a product initially came from,\nand what their journey looked like along the way.\nThese documents define how attribution works for the different products on our websites.\n1.20.1 Mozorg analytics\nGoogle Tag Manager (GTM)\nIn mozorg mode, bedrock uses Google Tag Manager (GTM) to manage and organize its Google Analytics solution.\nGTM (Google Tag Manager) is a tag management system that allows for easy implementation of Google Analytics\n(GA) tags and other 3rd party marketing tags in a nice GUI (Graphical User Interface) experience. Tags can be added,\nupdated, or removed directly from the GUI. GTM allows for a “one source of truth” approach to managing an analytics\nsolution in that all analytics tracking can be inside GTM.\nBedrock’s GTM solution is CSP (Content Security Policy) compliant and does not allow for the injection of custom\nHTML or JavaScript but all tags use built in templates to minimize any chance of introducing a bug into Bedrock.\nThe GTM DataLayer\nHow an application communicates with GTM is via the dataLayer object, which is a simple JavaScript array GTM\ninstantiates on the page. Bedrock will send messages to the dataLayer object by means of pushing an object literal\nonto the dataLayer. GTM creates an abstract data model from these pushed objects that consists of the most recent\nvalue for all keys that have been pushed to the dataLayer.\nThe only reserved key in an object pushed to the dataLayer is event which will cause GTM to evaluate the firing\nconditions for all tag triggers.\nDataLayer push example\nIf we wanted to track clicks on a carousel and capture what the image was that was clicked, we might write a dataLayer\npush like this:\ndataLayer.push({\n 'event': 'carousel-click',\n 'image': 'house'\n});\n1.20. Attribution 97\nbedrock Documentation, Release 1.0\nIn the dataLayer push there is an event value to have GTM evaluate the firing conditions for tag triggers, making it\npossible to fire a tag off the dataLayer push. The event value is descriptive to the user action so it’s clear to someone\ncoming in later what the dataLayer push signifies. There is also an image property to capture the image that is clicked,\nin this example it’s the house picture.\nIn GTM, a tag could be setup to fire when the event carousel-click is pushed to the dataLayer and could consume\nthe image value to pass on what image was clicked.\nThe Core DataLayer object\nFor the passing of contextual data on the user and page to GTM, we’ve created what we call the Core DataLayer Object.\nThis object passes as soon as all required API calls for contextual data have completed. Unless there is a significant\ndelay to when data will be available, please pass all contextual or meta data on the user or page here that you want to\nmake available to GTM.\nConditional banners\nWhen a banner is shown:\ndataLayer.push({\n 'eLabel': 'Banner Impression',\n 'data-banner-name': '', //ex. Fb-Video-Compat\n 'data-banner-impression': '1',\n 'event': 'non-interaction'\n});\nWhen an element in the banner is clicked:\ndataLayer.push({\n 'eLabel': 'Banner Clickthrough',\n 'data-banner-name': '', //ex. Fb-Video-Compat\n 'data-banner-click': '1',\n 'event': 'in-page-interaction'\n});\nWhen a banner is dismissed:\ndataLayer.push({\n 'eLabel': 'Banner Dismissal',\n 'data-banner-name': '', //ex. Fb-Video-Compat\n 'data-banner-dismissal': '1',\n 'event': 'in-page-interaction'\n});\n98 Chapter 1. Contents\n bedrock Documentation, Release 1.0\nA/B tests\nif(href.indexOf('v=a') !== -1) {\n window.dataLayer.push({\n 'data-ex-variant': 'de-page',\n 'data-ex-name': 'Berlin-Campaign-Landing-Page'\n });\n} else if (href.indexOf('v=b') !== -1) {\n window.dataLayer.push({\n 'data-ex-variant': 'campaign-page',\n 'data-ex-name': 'Berlin-Campaign-Landing-Page'\n });\n}\nGTM listeners & data attributes\nGTM also uses click and form submit listeners to gather context on what is happening on the page. Listeners push to\nthe dataLayer data on the specific element that triggered the event, along with the element object itself.\nSince GTM listeners pass the interacted element object to the dataLayer, the use of data attributes works very well when\ntrying to identify key elements that you want to be tracked and for storing data on that element to be passed into Google\nAnalytics. We use data attributes to track clicks on all downloads, buttons elements, and nav, footer, and CTA/button\nlink elements.\nImportant: When adding any new elements to a Bedrock page, please follow the below guidelines to ensure accurate\nanalytics tracking.\nFor all generic CTA links and