### Install Development Dependencies Source: https://haml.info/docs/yardoc Installs Haml's development gem dependencies using Bundler. Ensure Bundler is installed first. ```sh gem install bundler bundle install ``` -------------------------------- ### Haml Example in Rails Controller and View Source: https://haml.info/docs/yardoc/file.REFERENCE.html Example demonstrating how to use instance variables and helper methods in Haml templates within a Rails application. ```ruby # file: app/controllers/movies_controller.rb class MoviesController < ApplicationController def index @title = "Teen Wolf" end end ``` ```haml #- file: app/views/movies/index.html.haml #content .title %h1= @title = link_to 'Home', home_url ``` -------------------------------- ### Run Test Suite Source: https://haml.info/docs/yardoc Executes the entire test suite for Haml. This command should run without errors once dependencies are installed. ```sh rake ``` -------------------------------- ### Install Haml Gem Source: https://haml.info/docs/yardoc Install the Haml gem using the RubyGems package manager. ```bash gem install haml ``` -------------------------------- ### Haml CLI: Version Method Source: https://haml.info/docs/yardoc/Haml/CLI.html Prints the current version of the Haml library. Use this to check the installed Haml version. ```ruby def version puts Haml::VERSION end ``` -------------------------------- ### Haml Plain Text Example Source: https://haml.info/docs/yardoc/file.REFERENCE.html Demonstrates how lines not interpreted as Haml syntax are treated as plain text and passed through unmodified. ```haml %gee %whiz Wow this is cool! ``` -------------------------------- ### Haml Compiled Output in Rails Source: https://haml.info/docs/yardoc/file.REFERENCE.html The compiled HTML output for the provided Haml template example. ```html

Teen Wolf

Home
``` -------------------------------- ### HTML Boolean Attribute Example Source: https://haml.info/docs/yardoc/file.REFERENCE.html Demonstrates the HTML representation of a boolean attribute. ```html ``` -------------------------------- ### Multiline Ruby Code Example Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Demonstrates how Ruby code can span multiple lines in Haml templates when each line except the last ends with a comma. Useful for complex expressions or when readability is enhanced by breaking long lines. ```ruby = link_to_remote "Add to cart", :url => { :action => "add", :id => product.id }, :update => { :success => "cart", :failure => "error" } ``` -------------------------------- ### Example of escaped HTML with interpolation Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Demonstrates how Haml handles escaped HTML with interpolation, showing the difference in rendering before and after a bug fix. ```haml Foo < Bar #{"<"} Baz ``` ```text Foo &lt; Bar < Baz ``` ```text Foo < Bar < Baz ``` -------------------------------- ### Haml with Embedded HTML Example Source: https://haml.info/docs/yardoc/file.REFERENCE.html Shows how to include raw HTML within a Haml template; the HTML will be passed through unmodified. ```haml %p
Blah!
``` -------------------------------- ### Use Haml as a Standalone Ruby Module Source: https://haml.info/docs/yardoc/file.REFERENCE.html Example of using Haml as a standalone Ruby module by including the 'haml' gem and using Haml::Template. ```ruby engine = Haml::Template.new { "%p Haml code!" } engine.render #=> "

Haml code!

\n" ``` -------------------------------- ### Haml Plain Text Compiled Output Source: https://haml.info/docs/yardoc/file.REFERENCE.html The compiled HTML output for the Haml plain text example. ```html Wow this is cool! ``` -------------------------------- ### Compiled HTML for Whitespace Removal (`<`) Source: https://haml.info/docs/yardoc/file.REFERENCE.html Shows the HTML output when using `<` to remove whitespace immediately within a tag. This example illustrates its effect on block elements. ```html
Foo!
``` -------------------------------- ### Define a More Complex Custom Haml Filter Source: https://haml.info/docs/yardoc/file.REFERENCE.html This example demonstrates a more advanced custom filter that handles dynamic content and interpolations. It includes a private helper method for compiling text. ```ruby class BetterFilter < Haml::Filters::Base def compile(node) temple = [:multi] temple << [:static, "hello "] temple << compile_text(node.value[:text]) temple << [:static, " world"] temple end private def compile_text(text) if ::Haml::Util.contains_interpolation?(text) [:dynamic, ::Haml::Util.unescape_interpolation(text)] else [:static, text] end end end Haml::Filters.registered[:better] ||= BetterFilter ``` -------------------------------- ### Whitespace Removal with `>` and `<` in Haml Source: https://haml.info/docs/yardoc/file.REFERENCE.html Illustrates the combined use of `>` and `<` for whitespace control around and within tags. This example shows how `>` removes outer whitespace and `<` removes inner whitespace. ```haml %img %img> %img ``` ```haml %p<= "Foo\nBar" ``` ```haml %img %pre>< foo bar %img ``` -------------------------------- ### Haml Parser `compute_tabs` Method Source: https://haml.info/docs/yardoc/Haml/Parser.html Calculates the indentation level for a given line based on the established indentation string. Handles initial indentation setup and detects inconsistent indentation, raising SyntaxError if issues are found. ```ruby def compute_tabs(line) return 0 if line.text.empty? || !line.whitespace if @indentation.nil? @indentation = line.whitespace if @indentation.include?(?s) && @indentation.include?(? ) raise SyntaxError.new(Error.message(:cant_use_tabs_and_spaces), line.index) end @flat_spaces = @indentation * (@template_tabs+1) if flat? return 1 end tabs = line.whitespace.length / @indentation.length return tabs if line.whitespace == @indentation * tabs return @template_tabs + 1 if flat? && line.whitespace =~ /^#{@flat_spaces}/ message = Error.message(:inconsistent_indentation, human_indentation(line.whitespace), human_indentation(@indentation) ) raise SyntaxError.new(message, line.index) end ``` -------------------------------- ### Initialize DoctypeCompiler Source: https://haml.info/docs/yardoc/Haml/Compiler/DoctypeCompiler.html Initializes a new instance of DoctypeCompiler, setting the format option. ```ruby def initialize(options = {}) @format = options[:format] end ``` -------------------------------- ### Haml::Compiler::DoctypeCompiler#initialize Source: https://haml.info/docs/yardoc/Haml/Compiler/DoctypeCompiler.html Initializes a new instance of the DoctypeCompiler. It accepts an options hash, from which it extracts the :format setting. ```APIDOC ## Haml::Compiler::DoctypeCompiler#initialize ### Description Initializes a new instance of the DoctypeCompiler. It accepts an options hash, from which it extracts the :format setting. ### Method constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **DoctypeCompiler** (DoctypeCompiler) - A new instance of DoctypeCompiler. #### Response Example None ``` -------------------------------- ### Haml::Compiler::ChildrenCompiler#initialize Source: https://haml.info/docs/yardoc/Haml/Compiler/ChildrenCompiler.html Initializes a new instance of Haml::Compiler::ChildrenCompiler. It sets up internal variables and a multi-flattener for Temple. ```APIDOC ## Haml::Compiler::ChildrenCompiler#initialize ### Description Initializes a new instance of Haml::Compiler::ChildrenCompiler. It sets up internal variables and a multi-flattener for Temple. ### Method constructor ### Returns A new instance of ChildrenCompiler. ``` -------------------------------- ### Detect String Interpolation Source: https://haml.info/docs/yardoc/Haml/Util.html Checks if a string contains characters that indicate the start of an interpolation, specifically '#{', '$', or '@'. ```ruby # File 'lib/haml/util.rb', line 201 def contains_interpolation?(str) /#[\{$@]/ === str end ``` -------------------------------- ### Initialize Haml::Filters Source: https://haml.info/docs/yardoc/Haml/Filters.html Initializes a new instance of Haml::Filters with provided options and an empty compiler registry. ```ruby def initialize(options = {}) @options = options @compilers = {} end ``` -------------------------------- ### Haml::Parser#initialize Source: https://haml.info/docs/yardoc/Haml/Parser.html Initializes a new instance of the Haml::Parser. It sets up options, script level stack, template index, template tabs, and error raising behavior based on whether a generator is provided. ```APIDOC ## Haml::Parser#initialize ### Description Initializes a new instance of the Haml::Parser. It sets up options, script level stack, template index, template tabs, and error raising behavior based on whether a generator is provided. ### Method ```ruby def initialize(options) @options = ParserOptions.new(options) @script_level_stack = [] @template_index = 0 @template_tabs = 0 @raise_error = !options.key?(:generator) end ``` ### Parameters * **options** (Hash) - A hash of options to configure the parser. ``` -------------------------------- ### Class Method: render Source: https://haml.info/docs/yardoc/Haml/Filters/TiltBase.html Renders content using a Tilt template engine. It takes the template name, source code, and an optional indent width. If an indent width is provided, it indents the output accordingly. ```APIDOC ## Class Method: render ### Description Renders content using a Tilt template engine. It takes the template name, source code, and an optional indent width. If an indent width is provided, it indents the output accordingly. ### Method Class Method ### Parameters - **name** (String) - The name of the Tilt template. - **source** (String) - The source code to be rendered. - **indent_width** (Integer) - Optional. The number of spaces to indent the output by. Defaults to 0. ### Response - **text** (String) - The rendered and potentially indented text. ``` -------------------------------- ### Haml Class and ID Shortcuts Source: https://haml.info/docs/yardoc/file.REFERENCE.html Shows Haml syntax using '.' for class and '#' for ID, including chaining multiple classes. ```haml %div#things %span#rice Chicken Fried %p.beans{ :food => 'true' } The magical fruit %h1.class.otherclass#id La La La ``` -------------------------------- ### Universal Interpolation in Haml Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Use #{variable} for interpolating Ruby code within text. This example shows basic usage. ```Haml %p This is a really cool #{h what_is_this}! But is it a #{h what_isnt_this}? ``` -------------------------------- ### Haml with Embedded HTML Compiled Output Source: https://haml.info/docs/yardoc/file.REFERENCE.html The compiled HTML output for the Haml example containing embedded raw HTML. ```html

Blah!

``` -------------------------------- ### Haml::Compiler::ScriptCompiler#initialize Source: https://haml.info/docs/yardoc/Haml/Compiler/ScriptCompiler.html Initializes a new instance of ScriptCompiler. It takes an identity object and an options hash, setting up internal instance variables for processing. ```APIDOC ## Haml::Compiler::ScriptCompiler#initialize ### Description Initializes a new instance of ScriptCompiler. It takes an identity object and an options hash, setting up internal instance variables for processing. ### Method constructor ### Parameters * **identity**: The identity object for the compiler. * **options**: A hash containing options, such as `:disable_capture`. ``` -------------------------------- ### Haml CLI: Render Method Source: https://haml.info/docs/yardoc/Haml/CLI.html Renders a Haml file by processing load options, generating code, and evaluating it. Use this to see the direct output of a Haml file. ```ruby def render(file) process_load_options code = generate_code(file) puts eval(code, binding, file) end ``` -------------------------------- ### Get Registered Filters in Haml::Filters Source: https://haml.info/docs/yardoc/Haml/Filters.html Returns the value of the registered attribute, which is a collection of all currently registered Haml filters. ```ruby def registered @registered end ``` -------------------------------- ### Haml Nested Class and ID Shortcuts Source: https://haml.info/docs/yardoc/file.REFERENCE.html Demonstrates nested elements using class and ID shortcuts in Haml. ```haml %div#content %div.articles %div.article.title Doogie Howser Comes Out %div.article.date 2006-11-05 %div.article.entry Neil Patrick Harris would like to dispel any rumors that he is straight ``` -------------------------------- ### Escaping and Unescaping Interpolated Code in Haml Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Prefix interpolated lines with '&' to escape or unescape the Ruby code. This example demonstrates escaping. ```Haml %p& This is a really cool #{what_is_this}! & But is it a #{what_isnt_this}? ``` -------------------------------- ### Haml::HTML#initialize Source: https://haml.info/docs/yardoc/Haml/HTML.html Constructs a new instance of the HTML class. It handles deprecated formats by defaulting to :html and then calls the superclass constructor. ```APIDOC ## Haml::HTML#initialize ### Description Constructs a new instance of the HTML class. It handles deprecated formats by defaulting to :html and then calls the superclass constructor. ### Method constructor ### Parameters * **opts** (Hash) - Optional - Options for initialization. ### Request Example ```ruby Haml::HTML.new({ format: :xhtml }) ``` ### Response * **HTML** - A new instance of the HTML class. ``` -------------------------------- ### Preserving Whitespace in Textarea with Haml Source: https://haml.info/docs/yardoc/file.FAQ.html Haml automatically preserves whitespace for tags like textarea. This example shows the default behavior. ```Haml %p %textarea= "Foo\nBar" ``` -------------------------------- ### Haml::Filters#initialize Source: https://haml.info/docs/yardoc/Haml/Filters.html Initializes a new instance of the Filters class with given options. It sets up instance variables for options and compilers. ```APIDOC ## Haml::Filters#initialize ### Description Initializes a new instance of the Filters class with given options. It sets up instance variables for options and compilers. ### Method initialize ### Parameters #### Constructor Parameters - **options** (Hash) - Optional - Options for the filter. ### Response Returns a new instance of Filters. ``` -------------------------------- ### Inline ERB to Haml Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Converts inline ERB within HTML to inline Haml. For example, `

<%= foo %>

` becomes `%p= foo`. ```html

<%= foo %>

``` ```haml %p= foo ``` -------------------------------- ### Initialize Haml::HTML with Options Source: https://haml.info/docs/yardoc/Haml/HTML.html Initializes a new instance of Haml::HTML. Handles deprecated formats by converting them to :html. Calls the superclass constructor with the processed options. ```ruby def initialize(opts = {}) if DEPRECATED_FORMATS.include?(opts[:format]) opts = opts.dup opts[:format] = :html end super(opts) end ``` -------------------------------- ### Haml::ForceEscape#initialize Source: https://haml.info/docs/yardoc/Haml/ForceEscape.html Constructs a new instance of Haml::ForceEscape. It initializes the escape code and an escaper proc based on provided options or defaults. ```APIDOC ## Haml::ForceEscape#initialize ### Description Constructs a new instance of Haml::ForceEscape. It initializes the escape code and an escaper proc based on provided options or defaults. ### Method constructor ### Parameters * **opts** (Hash) - Optional - Options for initialization, potentially including `:escape_code`. ### Returns * ForceEscape - A new instance of ForceEscape. ``` -------------------------------- ### Inline HTML to Haml Text Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Transforms inline HTML text nodes into inline Haml text. For example, `

foo

` is converted to `%p foo`. ```html

foo

``` ```haml %p foo ``` -------------------------------- ### compile Source: https://haml.info/docs/yardoc/Haml/TemplateExtension.html Activates Haml::Helpers for tilt templates. This method extends the functionality of tilt templates by incorporating Haml's helper methods, allowing for more dynamic and feature-rich template rendering. ```APIDOC ## compile ### Description Activates Haml::Helpers for tilt templates. This method extends the functionality of tilt templates by incorporating Haml's helper methods, allowing for more dynamic and feature-rich template rendering. ### Method Instance Method ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Example ```ruby def compile(*) "extend Haml::Helpers; #{super}" end ``` ``` -------------------------------- ### Markdown Filter Example Source: https://haml.info/docs/yardoc/file.REFERENCE.html The `:markdown` filter processes indented Markdown content and converts it to HTML. It's useful for embedding formatted text within Haml templates. ```Haml %p :markdown # Greetings Hello, *World* ``` -------------------------------- ### Haml Help Command Source: https://haml.info/docs/yardoc Display help information for Haml command-line commands. ```bash haml --help ``` -------------------------------- ### Haml::Compiler::TagCompiler#initialize Source: https://haml.info/docs/yardoc/Haml/Compiler/TagCompiler.html Initializes a new instance of the TagCompiler. It sets up internal components like the autoclose flag, identity, and attribute compiler. ```APIDOC ## Haml::Compiler::TagCompiler#initialize ### Description Initializes a new instance of the TagCompiler. It sets up internal components like the autoclose flag, identity, and attribute compiler. ### Method constructor ### Parameters - **identity**: The identity object. - **options** (Hash): A hash of options, potentially including `:autoclose`. ### Request Example ```ruby tagCompiler.new(identity_object, { autoclose: true }) ``` ### Response - Returns a new instance of `TagCompiler`. ``` -------------------------------- ### Haml Ruby Block Execution Source: https://haml.info/docs/yardoc/file.REFERENCE.html Ruby blocks are automatically closed based on indentation. A block starts with increased indentation after a Ruby evaluation command and ends when indentation decreases. ```Haml - (42...47).each do |i| %p= i %p See, I can count! ``` ```HTML

42

43

44

45

46

See, I can count!

``` ```Haml %p - case 2 - when 1 = "1!" - when 2 = "2?" - when 3 = "3." ``` ```HTML

2?

``` -------------------------------- ### Basic Doctype and XML Prolog Source: https://haml.info/docs/yardoc/file.REFERENCE.html Generates a basic HTML document with an XML prolog. Use '!!!' for default doctype and '!!! XML' for XML prolog. ```Haml !!! XML !!! %html %head %title Myspace %body %h1 I am the international space station %p Sign my guestbook ``` ```HTML Myspace

I am the international space station

Sign my guestbook

``` -------------------------------- ### Haml::Escape#initialize Source: https://haml.info/docs/yardoc/Haml/Escape.html Initializes a new instance of the Escape class. It sets up the HTML escaping mechanism based on provided options. ```APIDOC ## Haml::Escape#initialize ### Description Initializes a new instance of the Escape class. It sets up the HTML escaping mechanism based on provided options. ### Method constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a new instance of Escape. #### Response Example None ``` -------------------------------- ### Render Haml File Source: https://haml.info/docs/yardoc Compile a Haml file to HTML using the Haml command-line interface. ```bash haml render document.haml ``` -------------------------------- ### Initialize Haml::Compiler::TagCompiler Source: https://haml.info/docs/yardoc/Haml/Compiler/TagCompiler.html Constructs a new instance of TagCompiler, setting up autoclose behavior, identity, and an attribute compiler. ```ruby def initialize(identity, options) @autoclose = options[:autoclose] @identity = identity @attribute_compiler = AttributeCompiler.new(identity, options) end ``` -------------------------------- ### Haml CLI: Parse Method Source: https://haml.info/docs/yardoc/Haml/CLI.html Generates and pretty-prints the Abstract Syntax Tree (AST) for a Haml file. Use this to understand the structure of the parsed Haml code. ```ruby def parse(file) pp_object(generate_ast(file), color: options[:color]) end ``` -------------------------------- ### Haml::Ambles#initialize Source: https://haml.info/docs/yardoc/Haml/Ambles.html Constructs a new instance of the Ambles class. It initializes instance variables for preamble and postamble based on provided options. ```APIDOC ## Haml::Ambles#initialize ### Description Returns a new instance of Ambles. This constructor initializes the instance with optional preamble and postamble values. ### Method constructor ### Parameters None explicitly documented for direct use, but accepts options for preamble and postamble. ### Request Example ```ruby ambles_instance = Haml::Ambles.new(options) ``` ### Response Returns a new instance of Ambles. ``` -------------------------------- ### Basic HTML Tag with Attributes Source: https://haml.info/docs/yardoc Create an HTML tag with attributes and content using Haml's shorthand syntax. ```haml %tagname{:attr1 => 'value1', :attr2 => 'value2'} Contents ``` -------------------------------- ### Haml CLI: Temple Method Source: https://haml.info/docs/yardoc/Haml/CLI.html Generates and pretty-prints the Temple AST for a given Haml file. Use this to inspect the intermediate Temple representation. ```ruby def temple(file) pp_object(generate_temple(file), color: options[:color]) end ``` -------------------------------- ### Initialize ForceEscape Source: https://haml.info/docs/yardoc/Haml/ForceEscape.html Initializes a new instance of ForceEscape, setting up the HTML escaping logic. It uses a configurable escape code or defaults to Haml::Util.escape_html. ```ruby def initialize(opts = {}) super @escape_code = options[:escape_code] || "::Haml::Util.escape_html((%s))" @escaper = eval("proc {|v| #{@escape_code % 'v'} }") end ``` -------------------------------- ### Haml::Ambles#call Source: https://haml.info/docs/yardoc/Haml/Ambles.html Processes an Abstract Syntax Tree (AST) by prepending and appending static content (preamble and postamble) if they exist. ```APIDOC ## Haml::Ambles#call ### Description Processes an Abstract Syntax Tree (AST). It optionally prepends a preamble and appends a postamble to the AST before returning the modified structure. ### Method call ### Parameters * **ast** (Array) - The Abstract Syntax Tree to process. ### Request Example ```ruby # Assuming 'ambles_instance' is an initialized Haml::Ambles object # and 'ast_data' is a valid AST structure result = ambles_instance.call(ast_data) ``` ### Response #### Success Response Returns an array representing the modified AST, potentially including preamble and postamble. - **ret** (Array) - The processed AST structure, starting with a multi-node, followed by preamble (if present), the original AST, and then the postamble (if present). ``` -------------------------------- ### Initialize ScriptCompiler Source: https://haml.info/docs/yardoc/Haml/Compiler/ScriptCompiler.html Initializes a new instance of ScriptCompiler with an identity and options. The disable_capture option is stored. ```ruby def initialize(identity, options) @identity = identity @disable_capture = options[:disable_capture] end ``` -------------------------------- ### Haml::Parser Constructor Source: https://haml.info/docs/yardoc/Haml/Parser.html Initializes a new instance of the Parser. It sets up options, script level stack, template index, template tabs, and error handling based on whether a generator is provided. ```ruby def initialize(options) @options = ParserOptions.new(options) # Record the indent levels of "if" statements to validate the subsequent # elsif and else statements are indented at the appropriate level. @script_level_stack = [] @template_index = 0 @template_tabs = 0 # When used in Haml::Engine, which gives options[:generator] to every filter # in the engine, including Haml::Parser, we don't want to throw exceptions. # However, when Haml::Parser is used as a library, we want to throw exceptions. @raise_error = !options.key?(:generator) end ``` -------------------------------- ### Initialize Haml::Ambles Source: https://haml.info/docs/yardoc/Haml/Ambles.html Initializes a new instance of Haml::Ambles. It sets up preamble and postamble options inherited from the parent class. ```ruby # File 'lib/haml/ambles.rb', line 6 def initialize(*) super @preamble = options[:preamble] @postamble = options[:postamble] end ``` -------------------------------- ### Haml::Parser::DynamicAttributes Source: https://haml.info/docs/yardoc/Haml/Parser/DynamicAttributes.html Provides documentation for the Haml::Parser::DynamicAttributes class, detailing its instance attributes and methods. ```APIDOC ## Class: Haml::Parser::DynamicAttributes Inherits: Struct * Object * Struct * Haml::Parser::DynamicAttributes Defined in: lib/haml/parser.rb ## Instance Attribute Summary * #**old** ⇒ Object writeonly Sets the attribute old. ## Instance Method Summary * #**to_literal** This will be a literal for Haml::HamlBuffer#attributes’s last argument, `attributes_hashes`. ## Instance Attribute Details ### #**old=**(value) ⇒ `Object` Sets the attribute old. Parameters: * value (`Object`) — the value to set the attribute old to. Returns: * (`Object`) — the newly set value ```ruby # File 'lib/haml/parser.rb', line 236 def old=(value) @old = value end ``` ## Instance Method Details ### #**to_literal** This will be a literal for Haml::HamlBuffer#attributes’s last argument, `attributes_hashes`. [View source] ```ruby # File 'lib/haml/parser.rb', line 246 def to_literal [new, stripped_old].compact.join(', ') end ``` ``` -------------------------------- ### Initialize Haml::Compiler Source: https://haml.info/docs/yardoc/Haml/Compiler.html Initializes a new instance of the Compiler class. It sets up various sub-compilers required for processing Haml AST nodes. ```ruby def initialize(options = {}) identity = Identity.new @children_compiler = ChildrenCompiler.new @comment_compiler = CommentCompiler.new @doctype_compiler = DoctypeCompiler.new(options) @filter_compiler = Filters.new(options) @script_compiler = ScriptCompiler.new(identity, options) @silent_script_compiler = SilentScriptCompiler.new @tag_compiler = TagCompiler.new(identity, options) end ``` -------------------------------- ### Define a Simple Custom Haml Filter Source: https://haml.info/docs/yardoc/file.REFERENCE.html This snippet shows how to define a basic custom Haml filter that outputs static text. It registers the filter under the :hello key. ```ruby class HelloFilter < Haml::Filters::Base def compile(_node) [:static, "hello world"] end end Haml::Filters.registered[:hello] ||= HelloFilter ``` -------------------------------- ### precede Source: https://haml.info/docs/yardoc/Haml/RailsHelpers.html Prepends a string to the captured Haml block's output, followed by a newline. Ensures the prepended string is HTML-safe if it's not already. ```APIDOC ## precede ### Description Prepends a given string to the output of a captured Haml block, followed by a newline. The prepended string is escaped if it's not already HTML-safe. ### Method Instance Method ### Parameters - `str` (String): The string to prepend. - `&block`: A Haml block whose captured output will follow the prepended string. ### Response - Returns an HTML-safe string with the `str` prepended to the captured block's output. ``` -------------------------------- ### Initialize Haml::AttributeCompiler Source: https://haml.info/docs/yardoc/Haml/AttributeCompiler.html Initializes a new instance of AttributeCompiler with identity, quote, format, and escape attributes options. ```ruby def initialize(identity, options) @identity = identity @quote = options[:attr_quote] @format = options[:format] @escape_attrs = options[:escape_attrs] end ``` -------------------------------- ### Initialize ChildrenCompiler Source: https://haml.info/docs/yardoc/Haml/Compiler/ChildrenCompiler.html Initializes a new instance of ChildrenCompiler, setting up internal state like the line number and a multi-flattener filter. ```ruby # File 'lib/haml/compiler/children_compiler.rb', line 7 def initialize @lineno = 1 @multi_flattener = Temple::Filters::MultiFlattener.new end ``` -------------------------------- ### Check for Explicit Tilt Registration Source: https://haml.info/docs/yardoc/Haml/Filters/TiltBase.html This instance method checks if an explicit Tilt registration is needed based on the Tilt version and whether the template is already registered. It's useful for managing dependencies and ensuring Tilt templates are available. ```ruby def explicit_require?(needed_registration) Gem::Version.new(Tilt::VERSION) >= Gem::Version.new('2.0.0') && !Tilt.registered?(needed_registration) end ``` -------------------------------- ### Instance Method: explicit_require? Source: https://haml.info/docs/yardoc/Haml/Filters/TiltBase.html Checks if a Tilt template registration is explicitly required based on the Tilt version and whether the template is already registered. This is used to ensure compatibility with Tilt versions and avoid redundant registrations. ```APIDOC ## Instance Method: explicit_require? ### Description Checks if a Tilt template registration is explicitly required based on the Tilt version and whether the template is already registered. This is used to ensure compatibility with Tilt versions and avoid redundant registrations. ### Method Instance Method ### Parameters - **needed_registration** (any) - The registration to check for. ### Response - **Boolean** - Returns `true` if explicit registration is needed, `false` otherwise. ``` -------------------------------- ### Haml::Parser#call Source: https://haml.info/docs/yardoc/Haml/Parser.html Parses the given Haml template string and returns the generated output. ```APIDOC ## Haml::Parser#call ### Description Parses the given Haml template string and returns the generated output. ### Method ```ruby def call(template) # ... implementation details ... end ``` ### Parameters * **template** (String) - The Haml template string to parse. ``` -------------------------------- ### Set Haml Options in Rails Initializer Source: https://haml.info/docs/yardoc/file.REFERENCE.html Configure Haml options globally for a Rails application by using Haml::RailsTemplate.set_options in an initializer. ```ruby # config/initializers/haml.rb Haml::RailsTemplate.set_options(escape_html: false) ``` -------------------------------- ### Compile CoffeeScript Node Source: https://haml.info/docs/yardoc/Haml/Filters/Coffee.html Compiles a CoffeeScript node using Tilt. Requires 'tilt/coffee' to be loaded if explicit_require? is true. Generates a script tag containing the compiled CoffeeScript. ```ruby def compile(node) require 'tilt/coffee' if explicit_require?('coffee') temple = [:multi] temple << [:static, ""] temple end ``` -------------------------------- ### Haml Data and Aria Attributes with False Source: https://haml.info/docs/yardoc/file.REFERENCE.html Demonstrates Haml syntax for data- and aria- attributes set to false, and their rendering. ```haml %input{'data-hidden' => false} %input{'aria-hidden' => false} %input{'xyz-hidden' => false} ``` -------------------------------- ### Haml::Error#initialize Source: https://haml.info/docs/yardoc/Haml/Error.html Initializes a new instance of the Haml::Error class. It accepts an optional error message and line number. ```APIDOC ## Haml::Error#initialize ### Description Initializes a new instance of the Haml::Error class. It accepts an optional error message and line number. ### Method initialize(message = nil, line = nil) ### Parameters * **message** (String) - Optional - The error message * **line** (Fixnum) - Optional - The line of the template on which the error occurred. ### Constructor Details Returns a new instance of Error. Parameters: * message (`String`) _(defaults to:` nil`)_ — The error message * line (`Fixnum`) _(defaults to:` nil`)_ — See #line ``` -------------------------------- ### Haml::RailsTemplate Instance Methods Source: https://haml.info/docs/yardoc/Haml/RailsTemplate.html Handles the compilation of Haml templates and checks for streaming support. ```APIDOC ## Instance Method: Haml::RailsTemplate#call(template, source = nil) ### Description Compiles a Haml template into Ruby code that can be rendered by Rails. It merges template-specific options and handles different content types. ### Method POST ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **template** (Object) - The Rails template object, containing source and other metadata. - **source** (String, optional) - The source code of the template. If nil, it's taken from `template.source`. ### Request Example ```ruby # Assuming 'template' is a Rails template object haml_template = Haml::RailsTemplate.new haml_template.call(template) ``` ### Response #### Success Response (200) - **compiled_code** (String) - The generated Ruby code from the Haml template. ## Instance Method: Haml::RailsTemplate#supports_streaming? ⇒ Boolean ### Description Checks if the current Haml configuration supports streaming output. ### Method GET ### Endpoint N/A (Instance Method) ### Parameters None ### Response #### Success Response (200) - **streaming_supported** (Boolean) - True if streaming is enabled, false otherwise. ### Response Example ```json { "streaming_supported": true } ``` ``` -------------------------------- ### Haml::Identity#initialize Source: https://haml.info/docs/yardoc/Haml/Identity.html Constructs a new instance of the Identity class. It initializes an internal counter for generating unique IDs. ```APIDOC ## Haml::Identity#initialize ### Description Initializes a new instance of the Identity class. This method sets up the internal state required for generating unique identifiers. ### Constructor `Identity.new` ### Returns A new instance of `Identity`. ``` -------------------------------- ### Set Haml Options Globally in Ruby Source: https://haml.info/docs/yardoc/file.REFERENCE.html Configure Haml options globally for non-Rails applications by setting them in Haml::Template.options. ```ruby Haml::Template.options[:escape_html] = false ``` -------------------------------- ### Process AST with Haml::Ambles Source: https://haml.info/docs/yardoc/Haml/Ambles.html Processes an Abstract Syntax Tree (AST) by prepending a preamble and appending a postamble if they are defined. This method is part of the Temple filter chain. ```ruby # File 'lib/haml/ambles.rb', line 12 def call(ast) ret = [:multi] ret << [:static, @preamble] if @preamble ret << ast ret << [:static, @postamble] if @postamble ret end ``` -------------------------------- ### Haml::Parser Call Method Source: https://haml.info/docs/yardoc/Haml/Parser.html Parses the given template. ```ruby def call(template) # ... (implementation details omitted for brevity) end ``` -------------------------------- ### Compile Markdown Node Source: https://haml.info/docs/yardoc/Haml/Filters/Markdown.html Compiles a Markdown node using Tilt. It conditionally requires 'tilt/redcarpet' if explicit_require? returns true for 'markdown'. ```ruby def compile(node) require 'tilt/redcarpet' if explicit_require?('markdown') compile_with_tilt(node, 'markdown') end ``` -------------------------------- ### Precede String with Haml Content Source: https://haml.info/docs/yardoc/Haml/RailsHelpers.html Prepends captured Haml content to a given string. Ensures the string is HTML-safe before prepending. Useful for adding dynamic content before static text. ```ruby def precede(str, &block) str = escape_once(str) unless str.html_safe? "#{str}#{capture_haml(&block).chomp}\n".html_safe end ``` -------------------------------- ### handle_interpolation Source: https://haml.info/docs/yardoc/Haml/Util.html Scans through a string looking for interpolation-opening `#{` and yields the scanner to the calling code to handle it properly. ```APIDOC ## #handle_interpolation(str) ### Description Scans through a string looking for the interpolation-opening `#{` and, when it’s found, yields the scanner to the calling code so it can handle it properly. This allows for custom interpolation logic. ### Method Instance Method ### Parameters * **str** (String) - The string to scan for interpolation. ### Response * Returns the string with interpolation handled. ### Request Example ```ruby Haml::Util.new.handle_interpolation("Hello #{name}!") do |scanner| # Custom handling logic here end ``` ### Response Example ```ruby # Returns the processed string with interpolation resolved. ``` ``` -------------------------------- ### Set Haml Options in Sinatra Source: https://haml.info/docs/yardoc/file.REFERENCE.html Configure Haml options for a Sinatra application using the set command. ```ruby set :haml, { escape_html: false } ``` -------------------------------- ### Compile Template in Haml::TempleEngine Source: https://haml.info/docs/yardoc/Haml/TempleEngine.html Compiles the given template using the call method. This method is part of the Haml::TempleEngine for Tilt integration. ```ruby def compile(template) @precompiled = call(template) end ``` -------------------------------- ### Using Ruby 1.9-style Hashes for Attributes Source: https://haml.info/docs/yardoc/file.REFERENCE.html Utilize Ruby's modern hash syntax (key: value) within Haml for specifying element attributes. ```Haml %a{title: @title, href: href} Stuff ``` -------------------------------- ### Combining Object Reference with `:class` Attribute Source: https://haml.info/docs/yardoc/file.REFERENCE.html Shows how to use an object reference alongside a `:class` attribute. The final element will have the union of classes from both sources. ```haml - user = User.find(1) %p[user]{:class => 'alpha bravo'} ``` -------------------------------- ### Haml::Escape Constructor Source: https://haml.info/docs/yardoc/Haml/Escape.html Initializes a new instance of Haml::Escape. It sets up the escape code based on provided options, defaulting to Haml::Util.escape_html or Haml::Util.escape_html_safe if use_html_safe is true. The escaper proc is then evaluated based on this code. ```ruby def initialize(opts = {}) super @escape_code = options[:escape_code] || "::Haml::Util.escape_html#{options[:use_html_safe] ? '_safe' : ''}((%s))" @escaper = eval("proc {|| #{@escape_code % 'v'} }") end ``` -------------------------------- ### Haml::AttributeParser.available? Source: https://haml.info/docs/yardoc/Haml/AttributeParser.html Checks if the AttributeParser can be used by verifying the availability of Ripper.lex and Temple::StaticAnalyzer. ```APIDOC ## Haml::AttributeParser.available? ### Description Checks if the AttributeParser can be used by verifying the availability of Ripper.lex and Temple::StaticAnalyzer. ### Method `Class` ### Returns * (`TrueClass`, `FalseClass`) - Returns `true` if `AttributeParser.parse` can be used, `false` otherwise. ### Source Code ```ruby # File 'lib/haml/attribute_parser.rb', line 10 def self.available? # TruffleRuby doesn't have Ripper.lex defined?(Ripper) && Ripper.respond_to?(:lex) && Temple::StaticAnalyzer.available? end ``` ``` -------------------------------- ### Haml Tag with CSS Selectors Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Illustrates the use of CSS selector shorthand within the `haml_tag` helper for creating elements with IDs and classes. Manually specified attributes are merged with selector-defined ones. ```ruby haml_tag('#foo') #=>
haml_tag('.bar') #=>
haml_tag('span#foo.bar') #=> ``` ```ruby haml_tag('span#foo.bar', :class => 'abc') #=> ``` ```ruby haml_tag('span#foo.bar', :id => 'abc') #=> ``` -------------------------------- ### HTML-Style Attribute Syntax Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Introduces HTML-style attribute syntax for Haml, offering a more concise and language-agnostic approach compared to Ruby's hash-style syntax. ```haml %a(href="https://haml.info" title="Haml's so cool!") %img(src="/images/haml.png" alt="Haml") ``` -------------------------------- ### Compile Haml::Helpers for Tilt Templates Source: https://haml.info/docs/yardoc/Haml/TemplateExtension.html Activates Haml::Helpers for tilt templates. This method is used to extend the template with Haml's helper methods. ```ruby def compile(*) "extend Haml::Helpers; #{super}" end ``` -------------------------------- ### Haml Equivalent of Merged Attributes Source: https://haml.info/docs/yardoc/file.REFERENCE.html Shows the equivalent Haml syntax for merging class and ID shortcuts with long-hand attributes. ```haml %div{:id => ['Article', @article.number], :class => ['article', 'entry', @article.visibility]} Gabba Hey ``` -------------------------------- ### Haml Recursive Data Attributes Source: https://haml.info/docs/yardoc/file.REFERENCE.html Demonstrates Haml's recursive expansion of nested data attribute hashes. ```haml .book-info{:data => {:book => {:id => 123, :genre => 'programming'}, :category => 7}} ``` -------------------------------- ### Compiling a Rails Template with Haml Source: https://haml.info/docs/yardoc/Haml/RailsTemplate.html Compiles a given Rails template using Haml. It retrieves template source, merges options based on template type (e.g., XML/XHTML), and applies annotations if enabled. Finally, it instantiates and calls the Haml::Engine. ```ruby # File 'lib/haml/rails_template.rb', line 26 def call(template, source = nil) source ||= template.source options = RailsTemplate.options # Make the filename available in parser etc. if template.respond_to?(:identifier) options = options.merge(filename: template.identifier) end # https://github.com/haml/haml/blob/4.0.7/lib/haml/template/plugin.rb#L19-L20 # https://github.com/haml/haml/blob/4.0.7/lib/haml/options.rb#L228 if template.respond_to?(:type) && template.type == 'text/xml' options = options.merge(format: :xhtml) end if ActionView::Base.try(:annotate_rendered_view_with_filenames) && template.format == :html options = options.merge( preamble: "\n", postamble: "\n", ) end Engine.new(options).call(source) end ``` -------------------------------- ### Autoclosing Tags Option Source: https://haml.info/docs/yardoc/file.CHANGELOG.html The Haml executable now accepts an `--autoclose` option to specify tags that should be autoclosed. ```bash haml --autoclose a,img,li,input,link,meta,br,hr ``` -------------------------------- ### Instantiate and Parse Attributes Source: https://haml.info/docs/yardoc/Haml/AttributeParser.html A convenience class method to create a new instance of AttributeParser and immediately call its parse method with the provided text. ```ruby def self.parse(text) self.new.parse(text) end ``` -------------------------------- ### Customizing Object Reference with `haml_object_ref` Source: https://haml.info/docs/yardoc/file.REFERENCE.html Demonstrates how to customize the class name used in object references by implementing the `haml_object_ref` method on the Ruby object. ```ruby # file: app/models/crazy_user.rb class CrazyUser < ActiveRecord::Base def haml_object_ref "a_crazy_user" end end ``` ```haml #- file: app/views/users/show.haml %div[@user] Hello! ``` -------------------------------- ### Array Attributes for :class and :id Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Demonstrates how Haml handles Ruby arrays for :class and :id attributes, including flattening and truthiness checks. ```Haml .column{:class => [@item.type, @item == @sortcol && [:sort, @sortdir]] } ``` ```HTML class="column numeric sort ascending" class="column numeric" class="column sort descending" class="column" ``` ```Haml .item{:class => @item.is_empty? && "empty"} ``` ```HTML class="item" class="item empty" ``` -------------------------------- ### Haml Merging Class/ID Shortcuts with Long-hand Attributes Source: https://haml.info/docs/yardoc/file.REFERENCE.html Illustrates how Haml merges class and ID shortcuts with explicit long-hand attributes. ```haml %div#Article.article.entry{:id => @article.number, :class => @article.visibility} ``` -------------------------------- ### HTML5 Custom Data Attributes Source: https://haml.info/docs/yardoc/file.CHANGELOG.html Shows how to generate HTML5 custom data attributes using a :data hash in Haml. ```Haml %div{:data => {:author_id => 123, :post_id => 234}} ``` ```HTML
``` -------------------------------- ### compile Source: https://haml.info/docs/yardoc/Haml/Compiler/SilentScriptCompiler.html Compiles a silent script node. If the node has no children, it compiles the node's text directly. Otherwise, it compiles the node with its children. ```APIDOC ## compile(node, &block) ### Description Compiles a silent script node. If the node has no children, it compiles the node's text directly. Otherwise, it compiles the node with its children. ### Method `compile` ### Parameters * **node**: The node to compile. * **block**: A block to be executed during compilation. ### Returns A multi-element array representing the compiled code, including the script text and newlines, or a compiled representation of the node and its children. ``` -------------------------------- ### Haml CLI: Method Missing Source: https://haml.info/docs/yardoc/Haml/CLI.html Handles dynamic method calls, forwarding calls with more than one argument to the superclass and rendering single-argument calls. This provides flexibility for CLI commands. ```ruby def method_missing(*args) return super(*args) if args.length > 1 render(args.first.to_s) end ``` -------------------------------- ### Class Name Merging and Ordering in Haml Source: https://haml.info/docs/yardoc/file.REFERENCE.html Illustrates how Haml merges and orders class names from different sources (tag identifiers, HTML attributes, Hash attributes). Note that older versions sorted alphabetically. ```haml .foo.moo{:class => ['bar', 'alpha']}(class='baz') ``` -------------------------------- ### Compile Less CSS in Haml Source: https://haml.info/docs/yardoc/Haml/Filters/Less.html This method compiles Less CSS content within a Haml node. It requires the 'tilt/less' library and formats the output within a '] temple end ``` -------------------------------- ### Compiled HTML for Combined Object Reference and Class Source: https://haml.info/docs/yardoc/file.REFERENCE.html The HTML output when an object reference is combined with an explicit `:class` attribute, demonstrating the merged class names. ```html

``` -------------------------------- ### Initialize Haml::Identity Source: https://haml.info/docs/yardoc/Haml/Identity.html Constructs a new instance of Haml::Identity, initializing the unique ID counter to 0. ```ruby def initialize @unique_id = 0 end ``` -------------------------------- ### Render Filtered Content with Tilt Source: https://haml.info/docs/yardoc/Haml/Filters/TiltBase.html This class method renders content using a Tilt template. It handles indentation for the output. Use this when you need to process source code through a Tilt-compatible engine within Haml. ```ruby def self.render(name, source, indent_width: 0) text = ::Tilt["t.#{name}"].new { source }.render return text if indent_width == 0 if text.frozen? text.gsub(/^/, ' ' * indent_width) else text.gsub!(/^/, ' ' * indent_width) end end ```