CssParser (CssParser v0.1.1) View Source

Provides css parsing in Elixir.

CssParser was inspired by css.js (a lightweight, battle tested, fast, css parser in JavaScript). More information can be found at https://github.com/jotform/css.js.

Adding CssParser

To add CssParser to an application, add it to deps in the mix.exs file:

  defp deps do
  [
    {:css_parser, ">= 0.1.0"}
  ]
end

Usage

You can use CssParser either on a command line or a module.

On command line

iex> CssParser.parse("h4, h3 {color: blue; font-size: 20px;}")
[
  %{
    rules: "color: blue; font-size: 20px;",
    selectors: "h4, h3",
    type: "elements"
  }
]

You can also parse css from a file as follows:

iex> CssParser.parse("/path/to/file.css")

In a module

CssParser can be aliased or imported in a module:

  defmodule MyMod do
    import CssParser

    def my_css_parser(css_string) do
      # use the imported `parse` function
      parse(css_string)
    end
  end

Recommendation

Enusure your css is valid to get valid results. Garbage in (maybe) garbage out. Kindly suggest improvements.

Link to this section Summary

Functions

Parses a css string to produce selectors, rules/descriptors and types. It first tries to remove css comments that might be in the css string.

Converts a parsed css to binary

Link to this section Functions

Specs

parse(binary()) :: [term()] | binary()

Parses a css string to produce selectors, rules/descriptors and types. It first tries to remove css comments that might be in the css string.

Examples

iex> CssParser.parse("h4, h3 {color: blue; font-size: 20px;}")
[
  %{
    rules: "color: blue; font-size: 20px;",
    selectors: "h4, h3",
    type: "elements"
  }
]

You can also parse css from a file as follows to get a string:

iex> CssParser.parse("/path/to/css/file.css")

In case the file path is invalid you'll get a relevant message such as No such file or directory.

Specs

to_binary([map()]) :: binary()

Converts a parsed css to binary

After running:

iex> parsed = CssParser.parse("h4, h3 {color: blue; font-size: 20px;}")

You can then get a (formatted) string as follows:

iex> CssParser.to_binary(parsed)
    "h4, h3 {
        color: blue; font-size: 20px;
     }"

The function is especially useful if you need to modify the parsed css structure and then get back a binary.